使用javascript从数组中筛选出数字索引
Filtering out numeric indexes from an array with javascript
这是我为从数组中筛选出数值而编写的代码,但它返回的是完整的数组。我无法找出代码中的问题。请帮帮我,我被卡住了。。。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>html demo</title>
</head>
<body>
<script>
arr = ["apple", 5, "Mango", 6];
function filterNumeric(arrayName){
var i = 0;
var numericArray=[];
for (i; i <arrayName.length;i++){
if (typeof(arrayName[i] === 'number')) {
numericArray+=arrayName[i];
}
}
return numericArray;
}
var filter = filterNumeric(arr);
alert(filter);
</script>
</body>
</html>
typeof
检查中的打字:
if (typeof(arrayName[i]) === 'number') {
// ^^^ close the parentheses here
// ^^^ not there
JavaScript数组有一个内置的过滤方法:
var arr = ["apple", 5, "Mango", 6];
var filtered = arr.filter(function(item) { return (typeof item === "number")});
console.log(filtered); // Array [5,6]
至于您的原始代码,请注意typeof
是一个运算符,而不是一个函数,因此
if (typeof(foo === "whatever")) {
// ...
}
相当于
if (typeof some_boolean_value) {
// ...
}
其评估为
if ("boolean") {
// ...
}
这将永远是真的,这就是为什么你最终得到的整个内容没有任何过滤。
还要注意的是,+=
运算符并没有重载数组,您最终会得到剩余值的字符串串接:
var foo = [];
var bar = [1,2,3,4];
foo += bar[2];
console.log(foo); // "3"
console.log(typeof foo); // "string"
必须使用push
方法:
var foo = [];
var bar = [1,2,3,4];
foo.push(bar[2]);
console.log(foo); // Array [3]
console.log(typeof foo); // "object"
相关文章:
- 测试索引值是否等于某个数字的倍数
- Angular js+ng repeat+字母数字索引不起作用
- 如果数字已插入排序数组,则获取该数字的索引
- for.in循环在非数字索引“clean”和“remove”上循环
- Javascript中的非数字索引多维数组
- 在数字索引循环中获取数组项的键
- 在数字索引处放置行 - SQL
- 通过 ajax 发送带有字母数字索引名称的数组
- 在数组中添加和减去数字索引值的类型转换
- 通过数字索引创建数组而不推入数组
- 非数字索引数组的长度
- 使用javascript从数组中筛选出数字索引
- 正在检查javascript数组中的数字索引
- 计数具有'仅限非数字索引'没有for在循环中
- Javascript数组与数字索引没有未定义
- 如何在javascript中获得关联数组中等效键的数字索引
- 循环对象属性vs数字索引数组
- 正在获取忽略数字索引的子字符串
- JS:将两个JSON对象合并为一个,但不制作数字索引
- javascript在使用数字索引分配数组值时是否调用. tostring ?