在JavaScript中,return
关键字用于从函数中返回一个值。当函数执行到return
语句时,它会立即停止执行,并将return
后面的表达式的值作为函数的返回值。如果没有指定返回值,或者return
后面没有跟任何表达式,那么函数会返回undefined
。
return
语句返回一个或多个值。return
语句会立即结束函数的执行。return
语句,或者return
后面没有值,函数默认返回undefined
。function add(a, b) {
return a + b;
}
console.log(add(1, 2)); // 输出: 3
function createUser(name, age) {
return {
name: name,
age: age,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
}
const user = createUser('Alice', 30);
user.greet(); // 输出: Hello, my name is Alice
function sayHello() {
console.log('Hello!');
}
sayHello(); // 输出: Hello!
console.log(sayHello()); // 输出: Hello! undefined
原因:
return
语句可能被遗漏。return
语句可能在条件分支中被错误地放置。return
语句之前抛出了异常。解决方法:
return
语句,并确保它们在正确的位置。function calculateDiscount(price, discountRate) {
if (typeof price !== 'number' || typeof discountRate !== 'number') {
return 'Invalid input';
}
return price * (1 - discountRate);
}
console.log(calculateDiscount(100, 0.1)); // 输出: 90
console.log(calculateDiscount('100', 0.1)); // 输出: Invalid input
通过这种方式,可以确保函数在所有情况下都有明确的返回值。