Heim > Fragen und Antworten > Hauptteil
1.判断 var uid ="5744242bc4c971005d5ff04e" 是否存在数组中,php有 in_array() 函数,js有比较方便的吗?
2.指定的uid 数组中的数值相加。
有没有不通过遍历的方式得到结果或者最简便的方式?
[
{
"uid": "5744242bc4c971005d5ff04e",
"num": 40,
"time": 1464150797000
},
{
"uid": "5744242bc4c971005d5ff04e",
"num": 12,
"time": 1464251797000
},
{
"uid": "574424e5df0eea0063adefc6",
"num": 10,
"time": 1464152873000
}
]
PHP中文网2017-04-11 10:37:44
题主表意不明。
如果是一维数组的话:
var sum = function (input, uid) {
return input.filter(function (i) { return i.uid === uid; }).reduce(function (f, s) { return f.num + s.num; });
};
sum([{"uid":"5744242bc4c971005d5ff04e","num":40,"time":1464150797000},{"uid":"5744242bc4c971005d5ff04e","num":12,"time":1464251797000},{"uid":"574424e5df0eea0063adefc6","num":10,"time":1464152873000}], '5744242bc4c971005d5ff04e');
如果是要按照题目中的二维数组,对于出现了指定 uid 的子数组分别进行求和的话:
var sum = function (input, uid) {
return input.filter(function (i) { return i.some(function (s) { return s.uid === uid; }); }).map(function (i) { return i.reduce(function (f, s) { return f + s.num; }, 0); });
};
sum([[{"uid":"5744242bc4c971005d5ff04e","num":40,"time":1464150797000}],[{"uid":"5744242bc4c971005d5ff04e","num":12,"time":1464251797000}],[{"uid":"574424e5df0eea0063adefc6","num":10,"time":1464152873000}]], '5744242bc4c971005d5ff04e');
怪我咯2017-04-11 10:37:44
你的需求和这个很像,你们是同学么?
https://segmentfault.com/q/1010000005330302/a-1020000005330807
需要检查数组中所有内容,不遍历怎么行?不过如果使用 map,可以加速循环体中的检索过程,具体实现你可以参考上面的链接
高洛峰2017-04-11 10:37:44
1.
var a = [
{
"uid": "5744242bc4c971005d5ff04e",
"num": 40,
"time": 1464150797000
},
{
"uid": "5744242bc4c971005d5ff04e",
"num": 12,
"time": 1464251797000
},
{
"uid": "574424e5df0eea0063adefc6",
"num": 10,
"time": 1464152873000
}
]
b = a.find( i => i.uid == '5744242bc4c971005d5ff04e');
console.log(b)
// Object {uid: "5744242bc4c971005d5ff04e", num: 40, time: 1464150797000}
2.
var a = [
{
"uid": "5744242bc4c971005d5ff04e",
"num": 40,
"time": 1464150797000
},
{
"uid": "5744242bc4c971005d5ff04e",
"num": 12,
"time": 1464251797000
},
{
"uid": "574424e5df0eea0063adefc6",
"num": 10,
"time": 1464152873000
}
]
a.filter(i => i.uid == '5744242bc4c971005d5ff04e').reduce((prev, curr) => (prev.num || prev) + curr.num);
// 52