javascript 在Javascript中将数字转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20730360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert number into array in Javascript
提问by user3127052
When I type a number with prompt var myNumber = parseInt(prompt("..."))
I want it to be converted into an array of numbers. When I try with myNumber = myNumber.split("")
it returns:
当我输入一个带有提示的数字时,var myNumber = parseInt(prompt("..."))
我希望它被转换成一个数字数组。当我尝试使用myNumber = myNumber.split("")
它时返回:
Object 1 has no method 'split'
对象 1 没有方法“拆分”
help me please
请帮帮我
采纳答案by Afzaal Ahmad Zeeshan
You cannot split the int, you need to have a string data type for this code to work!
您不能拆分 int,您需要有一个字符串数据类型才能使此代码工作!
So, I would like to suggest to first split it and then convert it to int as
所以,我想建议先拆分它,然后将其转换为 int 作为
var numbers = "1, 2, 3";
var eachNumber = numbers.split(",");
/* now parse them or whatso ever */
This will work, as you're just splitting the string. And then you will parse it just the way you did it in the first method (of yours).
这将起作用,因为您只是在拆分字符串。然后你将按照你在第一种方法(你的)中所做的方式解析它。
回答by Hallvar Helleseth
var intArray = prompt("...").split(" ").map(Number);
回答by Kelly J Andrews
You would need to change the number to string, then split it.
您需要将数字更改为字符串,然后将其拆分。
You would then want to return it to an integer.
然后,您可能希望将其返回为整数。
var myNumber = parseInt(prompt("Enter your number"));
var tempString = myNumber + "";
var arr = tempString.split("");
console.log(arr);
Here is a fiddle - http://jsfiddle.net/kellyjandrews/Wa5zD/
这是一个小提琴 - http://jsfiddle.net/kellyjandrews/Wa5zD/
回答by Praveen
myNumber
is an integer variable, which does not hold .split()
method, it belongs to string variable.
myNumber
是一个整型变量,不持有.split()
方法,属于字符串变量。
var no = "12 13 14 15";
var noV = no.split(" ")