use*_*019 0 arrays jquery multidimensional-array
我有一个我想搜索的数组。我找到了一种使用 $,map 的方法,但我无法使其正常工作。
我的数组是这样生成的:(使用从 MySQL 获取数据的 PHP 循环)
clientList.push = [{'ID' : '1', 'FullName' : 'Company1'}]
clientList.push = [{'ID' : '2', 'FullName' : 'Company2'}]
clientList.push = [{'ID' : '3', 'FullName' : 'Company3'}]
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用以下内容返回 ID = 2 的“FullName”值。这是另一个问题的示例。
var found = $.map(clientList, function(item) {
if (item.ID.indexOf('2') >= 0) {
return item;
}
});
if (found.length > 0) {
alert(found[0].FullName);
}
Run Code Online (Sandbox Code Playgroud)
但是,这不会返回任何内容,并且我没有收到任何 Javascript 错误。
我究竟做错了什么?
这是不正确的:
clientList.push = [{'ID' : '1', 'FullName' : 'Company1'}]
clientList.push = [{'ID' : '2', 'FullName' : 'Company2'}]
clientList.push = [{'ID' : '3', 'FullName' : 'Company3'}]
Run Code Online (Sandbox Code Playgroud)
您正在将数组分配给push属性,这是数组的一种方法。
如果您有一个从 引用的数组clientList,那么要添加到它,您可以调用 push(不=,并注意( ... );):
clientList.push([{'ID' : '1', 'FullName' : 'Company1'}]);
clientList.push([{'ID' : '2', 'FullName' : 'Company2'}]);
clientList.push([{'ID' : '3', 'FullName' : 'Company3'}]);
Run Code Online (Sandbox Code Playgroud)
另外,该$.map代码将无法正常工作,在项目clientList不具备的ID特性(他们的阵列;在对象里面他们有ID属性)。
你在评论中说:
我的目标是将 MySQL 表转储到可以搜索的 Jquery 数组中
那么你不想要一个对象数组的数组,只需要一个对象数组:
var clientList = []
// Presumably simulating the results of an ajax query
clientList.push({'ID' : '1', 'FullName' : 'Company1'});
clientList.push({'ID' : '2', 'FullName' : 'Company2'});
clientList.push({'ID' : '3', 'FullName' : 'Company3'});
Run Code Online (Sandbox Code Playgroud)
要在此处使用 找到条目 int ID == 2,您将使用Array#find(ES2015 中的新功能,但可填充/可填充):
var item = clientList.find(function(item) {
return item.ID == "2";
});
Run Code Online (Sandbox Code Playgroud)
现场示例:
clientList.push = [{'ID' : '1', 'FullName' : 'Company1'}]
clientList.push = [{'ID' : '2', 'FullName' : 'Company2'}]
clientList.push = [{'ID' : '3', 'FullName' : 'Company3'}]
Run Code Online (Sandbox Code Playgroud)