javascript找到数组项的父项(javascript find parent of array item)

编程入门 行业动态 更新时间:2024-10-12 01:29:39
javascript找到数组项的父项(javascript find parent of array item)

我有一个这样的数组项目:

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.

更多推荐

本文发布于:2023-08-04 11:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415680.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   find   javascript   item   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!