我有一个这样的数组项目:
var array = USA.NY[2]; // gives "Albany" {"USA" : { "NY" : ["New York City", "Long Island", "Albany"] }}我想从只有阵列中找到状态。 我该怎么做呢? 谢谢。
function findParent(array) { // do something // return NY }I have an array item like this:
var array = USA.NY[2]; // gives "Albany" {"USA" : { "NY" : ["New York City", "Long Island", "Albany"] }}I want to find the state from just having the array. How do I do this? Thanks.
function findParent(array) { // do something // return NY }最满意答案
在Javascript中,数组元素没有引用包含它们的数组。
为了达到这个目的,你将不得不引用'root'数组,这取决于你的数据模型。 假设美国是可访问的,并且只包含数组,你可以这样做:
function findParent(item) { var member, i, array; for (member in USA) { if (USA.hasOwnProperty(member) && typeof USA[member] === 'object' && USA[member] instanceof Array) { array = USA[member]; for(i = 0; i < array.length; i += 1) { if (array[i] === item) { return array; } } } } }请注意,我已将array参数重命名为item因为您正在传递一个值(和数组项),并且您期望返回该数组。 如果你想知道数组的名字 ,你应该返回member 。
In Javascript, array elements have no reference to the array(s) containing them.
To achieve this, you will have to have a reference to the 'root' array, which will depend on your data model. Assuming USA is accessible, and contains only arrays, you could do this:
function findParent(item) { var member, i, array; for (member in USA) { if (USA.hasOwnProperty(member) && typeof USA[member] === 'object' && USA[member] instanceof Array) { array = USA[member]; for(i = 0; i < array.length; i += 1) { if (array[i] === item) { return array; } } } } }Note that I’ve renamed the array parameter to item since you’re passing along a value (and array item), and you expect the array to be returned. If you want to know the name of the array, you should return member instead.
更多推荐
发布评论