问题描述
具有一个返回对象数组的函数.该数组具有一个rate对象,该对象具有一个名称字段.名称字段内是诸如慢速"和最快"的名称.
Have a function that returns an array of objects. The array has a rate object that has a name field. Inside the name field are names such as "Slow speed" and "Fast speed".
我写了以下文章,希望创建一个新的数组,该数组将过滤出数组值,只返回那些与rate [i] .name相匹配的慢"值.
I have written the following in hopes to create a new array that will filter out the array values and just return only those with "Slow" that matches from the rates[i].name.
到目前为止,我在开发人员控制台中遇到此错误.未捕获的TypeError:value.substring不是函数"
So far I am encountering this error in my dev console."Uncaught TypeError: value.substring is not a function"
var rates = myArray();
var index, value, result;
var newArr = [];
for (index = 0; index < rates.length; ++index) {
//value = rates[index];
if (value.substring(0, 5) === "Stand") {
result = value;
newArr.push();
break;
}
}
在控制台中返回数组的一部分.
Part of array return in console.
"rates":[{"id":1123,"price":"1.99","name":"Slow speed - Red Car","policy":{"durqty":1,"durtype":"D","spdup":15000,"spddwn":15000}
推荐答案
您在每个数组位置都有一个对象,而不是字符串本身,请尝试以下操作:
You have an object at each array location not the string itself, try this instead:
var rates = myArray();
var index, value, result;
var newArr = [];
for (index = 0; index < rates.length; ++index) {
name = rates[index].name;
if (name.substring(0, 4) === "Slow") {
newArr.push(rates[index]);
}
}
尝试使用 filter
这样的函数,查看起来更加干净
Try using filter
function like this, it is much more cleaner to see
var newArr = rates.filter(function(rate){
return rate.name && rate.name.substring(0,4) === "Slow";
});
这篇关于Javascript搜索数组中的部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!