javascript - JavaScript 数组过滤器返回未定义
问题描述
我试图了解在使用不同的语法/方法编写函数时适用于数组映射的规则。
var MyArray = ["Item1", "Item2", "Item3", "Item4"]
function removeEveryOther(array){
array.filter(function(value, index) {
return index % 2 === 0;
})
}
var Filtered = MyArray.removeEveryOther;
console.log(Filtered);
我想使用过滤器从数组中删除所有其他元素。由于某种原因,上述返回未定义,为什么?
解决方案
首先,您需要在此处返回.filter()
方法结果,例如:
function removeEveryOther(array) {
return array.filter(function(value, index) {
return index % 2 === 0;
})
}
否则,您正在做的主要是返回 undefined ,例如:
function removeEveryOther(array) {}
console.log( removeEveryOther([]) ) //=> returns "undefined"
然后,您需要removeEveryOther()
通过传递数组来正确调用该函数,例如:
var Filtered = removeEveryOther(MyArray);
console.log(Filtered);
演示(ES5):
var MyArray = ["Item1", "Item2", "Item3", "Item4"]
function removeEveryOther(array){
return array.filter(function(value, index) {
return index % 2 === 0;
})
}
var Filtered = removeEveryOther(MyArray);
console.log(Filtered);
演示(ES6):
var MyArray = ["Item1", "Item2", "Item3", "Item4"]
function removeEveryOther(array){
return array.filter((value, index) => index % 2 === 0);
}
var Filtered = removeEveryOther(MyArray);
console.log(Filtered);
推荐阅读
- javascript - 在离子/角度中将字符串日期“d/m/y”格式化为“dd/mm/yyyy”
- python - 使用 gspread 创建的电子表格正在与我组织中的所有用户共享
- python-3.x - 将数据框中的所有项转换为浮点数
- python - 如何保存通过camera.capture_continuous(格式rgb)读取的图像并将其保存到文件中
- reactjs - 用于 React 挂钩常量的 useMemo 与 useState
- javascript - 过渡问题 CSS 和 JS
- swift - 如何在 swift setMethodCallHandler 中使用传递的参数 - self?.methodName(result: result)
- qmail - 一个帐户正在迁移。如何停止该单个域的本地传递并使用不同的邮件服务器?
- php - 如何将 PDO 转换为 MYSQLi
- java - 如何解决spring-boot的冲突实体