简体   繁体   English

如何在Javascript中的函数中引用数组方法

[英]How to reference an array method within a function in Javascript

var myList = ["Hello There World", "meatball", "cookie monster"];

var BreakUpFirst = function (myList) {
document.write(myList[0].split(" "));
};

Hello I am new to JavaScript so please bear with me. 您好,我是JavaScript新手,请多多包涵。 Not sure what I am doing wrong here. 不知道我在做什么错。

I am trying to break the first string in the myList array into its own array with 3 values. 我正在尝试将myList数组中的第一个字符串myList成具有3个值的自己的数组。 The split method works fine for me outside of the function, but I can't get it to work inside. split方法在函数外部对我来说很好用,但是我无法在内部使用它。 I want to create BreakUpFirst as a new array and keep myList or any other array I pass through it as is. 我想将BreakUpFirst创建为新数组,并保留myList或我通过它的任何其他数组。

You're actually doing a couple of different things here. 您实际上在这里做了几件不同的事情。 If you just want to assign the value of myList[0].split(" ") to var BreakUpFirst , then the solution suggested by @thefourtheye is ideal. 如果仅要将myList[0].split(" ")的值分配给var BreakUpFirst ,则@thefourtheye建议的解决方案是理想的。 Just assign the value directly: 只需直接分配值:

var BreakUpFirst = myList[0].split(" ");

If you're trying to use a function that will always break up a string stored at the first element of an array and output it to the screen, then you need to make sure you pass in the array as a parameter. 如果您尝试使用一个函数,该函数将始终分解存储在数组第一个元素中的字符串并将其输出到屏幕,则需要确保将数组作为参数传递。 If you define your function: 如果定义函数:

 var BreakUpFirst = function(myList) {
     return myList[0].split(" ");
 }

 var myList = ["Hello There World", "meatball", "cookie monster"];

You need to make sure you invoke the function and pass in the parameter : 您需要确保调用该函数并传递参数

 var brokenString = BreakUpFirst(myList);
 alert(brokenString);

You will get an alert box with the brokenString array, "Hello","There","World" 您将收到一个带有brokenString数组的警报框, "Hello","There","World"

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

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