return实现js
实现 return 的 JavaScript 方法
在 JavaScript 中,return 语句用于从函数中返回值。以下是几种常见的实现方式:
基本函数返回
function add(a, b) {
return a + b;
}
const result = add(2, 3); // 返回 5
箭头函数返回
const multiply = (a, b) => {
return a * b;
};
const product = multiply(4, 5); // 返回 20
隐式返回(箭头函数)
const square = x => x * x; // 隐式返回 x * x
const squaredValue = square(3); // 返回 9
提前返回
function checkAge(age) {
if (age < 18) {
return "未成年";
}
return "成年";
}
const status = checkAge(20); // 返回 "成年"
返回对象(需括号包裹)
const getUser = () => ({
name: "Alice",
age: 25
});
const user = getUser(); // 返回 { name: "Alice", age: 25 }
返回 Promise
async function fetchData() {
return await fetch('https://api.example.com/data');
}
fetchData().then(data => console.log(data));
注意事项:
- 函数中遇到
return会立即终止执行 - 未显式指定
return的函数默认返回undefined - 箭头函数单行表达式可省略
return和花括号 - 返回对象字面量时需用括号包裹以避免语法歧义







