Reset an array through function parameter

This question already has an answer here:

  • How do I empty an array in JavaScript? 18 answers

  • user3378165 gave the correct answer:

    <script>
    fruitArray = ["apple", "banana", "orange", "pineapple"];
    function newFruit(myArray){
      myArray.length = 0;
    }
    newFruit(fruitArray);
    alert(fruitArray[0]);//Returns "apple"
    </script>
    

    Actually, the question is by value topic, you can learn more here: In practical terms, this means that if you change the parameter itself (as you did), that won't affect the item that was fed into the parameter. But if you change the INTERNALS of the parameter(array.length = 0), that will propagate back up


    Do like this. Set the length to 0

    myArray.length = 0
    

    You don't set your array with the change you made, you send to the newFruit function an array, you change it but this has nothing to do with your fruitArray .

    So all you have to do is to return the changed array from the function and to set your fruitArray with the array returned from the function, as follow:

        fruitArray = ["apple", "banana", "orange", "pineapple"]
        function newFruit(myArray){
           myArray = [];
           return myArray;
        }
        fruitArray = newFruit(fruitArray);
        alert(fruitArray[0]);//Returns "undefined" because there is no a [0] place in the fruitArray.
        alert(fruitArray);//Returns ""-empty array.
    链接地址: http://www.djcxy.com/p/23958.html

    上一篇: 如何遍历TreeMap?

    下一篇: 通过函数参数重置一个数组