返回信息流我邮的大牛们,小白又来召唤大神了[ema1]
想问一下js有没有对数组进行查找特定数据的函数,方法什么的。。。类似于stl中list.find()那种。
数组中的元素是类似于这种:{ "firstName":"Thomas" , "lastName": "Carter" }
数组类似于这种:
var employees = [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName": "Carter" }
];
想按firstname lastname 查找对应的某一组或几组数据。
谢谢大神们了[ema23]
这是一条镜像帖。来源:北邮人论坛 / www-technology / #28705同步于 2014/12/18
该镜像源已超过 30 天没有更新,可能在源站已被删除。
WWWTechnology机器人发帖
小白求问关于数组查找
airfan
2014/12/18镜像同步11 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
我在自学中,简单写了一个。。。
function findEmployee(fName,lName){
var i;
var query;
var results = [];
query = arguments[0];
if(arguments.length==0){
console.log('是不是忘记输入了?');
return
}
for(i=0;i<employees.length;i++){
if(arguments.length==1){
if(employees[i].firstName==query||employees[i].lastName==query){
results.push(employees[i]);
console.log(results);
}
}
else if(arguments.length==2){
if(employees[i].firstName==fName&&employees[i].lastName==lName){
results.push(employees[i]);
console.log(results);
}
}
}
if(results.length==0){
console.log('没有这个人!');
}
}
findEmployee();
【 在 airfan 的大作中提到: 】
: 我邮的大牛们,小白又来召唤大神了
: 想问一下js有没有对数组进行查找特定数据的函数,方法什么的。。。类似于stl中list.find()那种。
: 数组中的元素是类似于这种:{ "firstName":"Thomas" , "lastName": "Carter" }
: ...................
有,不过是es6才支持。Array.prototype.find();
polyfill:
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
if(arguments.length==1){
if(employees[i].firstName==query||employees[i].lastName==query){
results.push(employees[i]);
console.log(results);
}
}
这段什么意思?
arguments是什么啊?
【 在 orifake 的大作中提到: 】
: 我在自学中,简单写了一个。。。
: [code=js]
: function findEmployee(fName,lName){
: ...................
可以输入first或者lastname中的一个查询。arguments函数的局部变量,包含调用时候的实参。
【 在 picls 的大作中提到: 】
: if(arguments.length==1){
: if(employees[i].firstName==query||employees[i].lastName==query){
: results.push(employees[i]);
: ...................
谢谢大神,我试一试
【 在 orifake 的大作中提到: 】
: 我在自学中,简单写了一个。。。
: [code=js]
: function findEmployee(fName,lName){
: ...................