Javascript搜索数组中的部分字符串
具有一个返回对象数组的函数。数组有一个rate对象,该对象有一个name字段。名称字段中有“慢速”和“快速”等名称 我写了以下内容,希望创建一个新数组,该数组将过滤掉数组值,只返回那些与速率[I].name匹配的“Slow”值 到目前为止,我在我的开发控制台中遇到了这个错误。 “未捕获类型错误:value.substring不是函数”Javascript搜索数组中的部分字符串,javascript,arrays,Javascript,Arrays,具有一个返回对象数组的函数。数组有一个rate对象,该对象有一个name字段。名称字段中有“慢速”和“快速”等名称 我写了以下内容,希望创建一个新数组,该数组将过滤掉数组值,只返回那些与速率[I].name匹配的“Slow”值 到目前为止,我在我的开发控制台中遇到了这个错误。 “未捕获类型错误:value.substring不是函数” var rates=myArray(); var指数、价值、结果; var newArr=[]; 对于(索引=0;索引
var rates=myArray();
var指数、价值、结果;
var newArr=[];
对于(索引=0;索引
在控制台中返回部分数组
"rates":[{"id":1123,"price":"1.99","name":"Slow speed - Red Car","policy":{"durqty":1,"durtype":"D","spdup":15000,"spddwn":15000}
如果每个数组位置都有一个对象,而不是字符串本身,请尝试以下操作:
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
执行此操作,例如:
var newArr = rates.filter(function(val){
// check if this object has a property `name` and this property's value starts with `Slow`.
return val.name && val.name.indexOf("Slow") == 0;
});
正如@4castle提到的,您可以使用可能更有效的
slice(…)
来代替(…)的indexOf(…)
,例如:val.name.slice(0,4)=“Slow”
值的可能副本是array特定索引处的对象。您可能需要执行value.name
操作,还需要使用newArr.push(结果)代码>不要中断
如果希望newArr
存储的不仅仅是第一个匹配项。indexOf
将查看整个字符串。如果他们只想查看前4个字符,他们应该使用slice(0,4)==“Slow”
前4个字符将位于子字符串(0,4)
下,您为name
赋值,然后检查value.substring
,当子字符串(0,5)
返回带空格的单词“Slow”
所以它不会匹配慢“
是的,你是对的,我的坏朋友。正在编辑他的代码,没有注意。谢谢,编辑
var newArr = rates.filter(function(val){
// check if this object has a property `name` and this property's value starts with `Slow`.
return val.name && val.name.indexOf("Slow") == 0;
});