简体   繁体   English

Javascript返回具有原始值的数组索引的引用

[英]Javascript return reference to array index with primitive value

I want to return a reference to to the content of an array at index x in order to be able to change the content of the array using the returned index afterwards. 我想返回对索引x处的数组内容的引用,以便以后可以使用返回的索引来更改数组的内容。 Here is an example of what I mean: 这是我的意思的示例:

let testArr = [1,2,3]
const someFunct = arr => {
    ...
    return {reference to arr[0], aka 1}
}
someFunct(testArr) = 0;

//should log [0,2,3]
console.log(testArr);

someFunct(testArr) should behave like arr[0] in this case. 在这种情况下, someFunct(testArr)行为应类似于arr[0]
The content of the array could be anything. 数组的内容可以是任何东西。

i dont think the exact implementation you are trying to achieve is possible in JavaScript. 我不认为您要实现的确切实现可以在JavaScript中实现。

https://medium.com/@naveenkarippai/learning-how-references-work-in-javascript-a066a4e15600 https://medium.com/@naveenkarippai/learning-how-references-work-in-javascript-a066a4e15600

something similar: 相似的东西:

const testArr = [1,2,3]
const changeArray = (array, index, newValue) => {
    array[index] = newValue
    return array
}

changeArray(testArr, 0, 0) // evaluates to [0,2,3]

I want to return a reference … 我想返回一个参考...

This is not possible, JavaScript doesn't have references as returnable values. 这是不可能的,JavaScript没有将引用作为可返回值。 The someFunct(testArr) = 0; someFunct(testArr) = 0; syntax you are imagining is invalid. 您想象中的语法无效。

Instead, take the new value as an argument: 相反,将新值用作参数:

function someFunct(arr, val) {
    …
    arr[0] = val;
}
someFunct(testArr, 0);

or return an object with a method that does the assigning: 或使用执行分配的方法返回对象:

function someFunct(arr) {
    …
    return {
        set(v) {
            arr[0] = v;
        }
    };
}
someFunct(testArr) = 0;

Try this: 尝试这个:

  function arrayWrapper(arr, index, newVal) { let returnVal; if(newVal) { arr[index] = newVal; returnVal = arr; } else { const obj = { ...arr }; returnVal = obj[index]; } return returnVal; }; console.log(arrayWrapper([1,2,3,4,5,6,7,8,9], 5)); /// to get value at index console.log(arrayWrapper([1,2,3,4,5,6,7,8,9], 5, 'text')); // to set value on index 

You can use the above method to get as well as set elements to your array. 您可以使用上述方法获取设置数组元素。 The nature of operation depends on the third parameter. 操作的性质取决于第三个参数。

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM