我遍历一个数组,并根据条件我想为对象添加不同的值。
第一个console.log()输出值。第二个不输出任何东西。为什么?我能做些什么呢?期望的结果是,如果任何关键字在nicecontact.fulladress中,则应该使用该关键字对字符串进行拆分和添加。如果没有值,我想要fulladress =地址
var niceContact= {}
niceContact.fulladress = $.trim(contact[2])
//cut out lgh if it's in there.
var keywords = ["Lgh", "lgh"]
niceContact.adress = keywords.some(function(keyword){
if (niceContact.fulladress.indexOf(keyword) != -1){
adressarray = niceContact.fulladress.split(keyword)
niceContact.adress = adressarray[0]
console.log(niceContact.adress)
return adress;
}else{
console.log('false')
niceContact.adress = niceContact.fulladress
}
})
console.log(niceContact.adress)
答案 0 :(得分:1)
这不是Array.some
的用途。不应该从它返回一个值:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
一些对数组中存在的每个元素执行一次回调函数,直到找到一个回调返回true值的元素。如果找到这样的元素,则会立即返回true。否则,有些返回false。仅为已分配值的数组的索引调用回调;对于已删除或从未分配过值的索引,不会调用它。
var niceContact= {}
var hadHit = false
niceContact.fulladress = $.trim(contact[2])
//cut out lgh if it's in there.
var keywords = ["Lgh", "lgh"]
niceContact.adress = niceContact.fulladress
keywords.forEach(function(keyword){
if (!hadHit && niceContact.adress.indexOf(keyword) != -1){
// do your checking for the keywords here
// and modify niceContact.adress if needed
// if you're looking to `break` out of the .forEach
// you can `return false;` instead (same as break) see http://stackoverflow.com/questions/6260756/how-to-stop-javascript-foreach
// or if you have a hit, just do `hadHit = true` after mod-ing the address
}
})
console.log(niceContact.adress)