标签:条件 怎么 mon ace mil 数组 class src size
1.filter通常情况下是用来返回一个符合条件的新数组的,并且他不会对原数组产生影响:
comment_or_reply_id: "ob8qj0xq8e5s", from_uid: "1502039268@qq.com", isAgreeClick: true, topic_id: "604629fd0344202df0b22d81", topic_type: "nous_articles" }, { comment_or_reply_id: "1", from_uid: "666", isAgreeClick: true, topic_id: "604629fd0344202df0b22d81", topic_type: "nous_articles" } ] let crr = { from_uid: "1502039268@qq.com", comment_id: ‘ob8qj0xq8e5s‘ } let b = arr.filter(function (curentV, index, arr) { return curentV.from_uid == crr.from_uid && curentV.comment_or_reply_id == crr.comment_id }) console.log(b)
运行结果:
[ { comment_or_reply_id: ‘ob8qj0xq8e5s‘, from_uid: ‘1502039268@qq.com‘, isAgreeClick: true, topic_id: ‘604629fd0344202df0b22d81‘, topic_type: ‘nous_articles‘ } ]
但是我只是要拿到里面的isAgreeClick怎么做呢?
这样吗:
let b = arr.filter(function (curentV, index, arr) { return curentV.from_uid == crr.from_uid && curentV.comment_or_reply_id == crr.comment_id })[0].isAgreeClick console.log(b)
运行结果:true,的确拿到了该值,但是此种做法的弊端就是,当filter里面的条件没有匹配到时,会返回一个空数组,此时对空数组取值就会报错!
例子:还是刚才那段代码,但是此时comment_or_reply_id为1了,此时匹配不到就会报错
let arr = [{ comment_or_reply_id: "1", from_uid: "1502039268@qq.com", isAgreeClick: true, topic_id: "604629fd0344202df0b22d81", topic_type: "nous_articles" }, { comment_or_reply_id: "1", from_uid: "666", isAgreeClick: true, topic_id: "604629fd0344202df0b22d81", topic_type: "nous_articles" } ] let crr = { from_uid: "1502039268@qq.com", comment_id: ‘ob8qj0xq8e5s‘ } let b = arr.filter(function (curentV, index, arr) { return curentV.from_uid == crr.from_uid && curentV.comment_or_reply_id == crr.comment_id })[0].isAgreeClick console.log(b)
如何处理呢,下面给出方案:就是把后面数组的返回结果附上布尔值,就可以进行拿到里面的bool值了,但是此种做法只针对布尔值有效,想要拿到里面的其它类型元素的值,
而且在空数组我下仍然不会报错的话,我暂时没有思路。
let b = arr.filter(function (curentV, index, arr) { return curentV.from_uid == crr.from_uid && curentV.comment_or_reply_id == crr.comment_id })==false console.log(b)
上面运行结果:
标签:条件 怎么 mon ace mil 数组 class src size
原文地址:https://www.cnblogs.com/hmy-666/p/14617440.html