简体   繁体   English

可以将单个Javascript var视为数组吗?

[英]Possible to treat singular Javascript var as an array?

Whilst I am sure there's a duplicate question of this out there, because I am unfamiliar with javascript, I don't know the proper term, and thus wouldn't know where to start searching for it (if I knew what it was called, I'd just read up about it). 尽管我可以肯定有一个重复的问题,因为我不熟悉javascript,但我不知道合适的术语,因此也不知道从哪里开始搜索(如果我知道它叫什么,我只是读了一下)。

I have a singular var (that is not an array) that contains a set of numbers: 我有一个包含一组数字的单数var( 不是数组):

var Latitude = Math.floor(Math.random()*90) + Math.random();

I want to encode all numbers contained in Latitude, including the numbers after the floating point (and including the floating point, and any minus signs - although note this code example doesn't add a minus sign) into an array of letters, so 0 = A, 1 = B, so on. 我想将“纬度”中包含的所有数字编码,包括浮点数(包括浮点数和任何减号-尽管请注意此代码示例未添加减号)之后的数字到一个字母数组中,所以0 = A,1 = B,依此类推。

Is there any simple way of converting the singular var into an array of individual numbers for encoding? 有没有简单的方法可以将var转换为单个数字数组进行编码?

First, slight typo in your question, Math.random is a function. 首先,您的问题中有轻微的错字, Math.random是一个函数。 You want to convert the number you get to a string, the easiest way to do this is to add an empty string - '' . 要转换你到一个字符串的数字,要做到这一点最简单的方法是添加一个空字符串- '' Then just use the split function to break the string into an array: 然后只需使用split函数将字符串分成一个数组即可:

var Latitude = ((Math.floor(Math.random()*90) + Math.random()) + '').split('');
var latitude = new Array();
latitude.value = Math.floor(Math.random*90) + Math.random();
latitude.push(2);//demonstrating that it's an array;
console.log(latitude.value);//for testing purposes only
console.log(latitude);//for testing purposes only

Now you can use latitude's value but also use it as an array. 现在,您可以使用纬度值,也可以将其用作数组。

edit Sorry, I seem to have misread your question. 编辑抱歉,我似乎误读了您的问题。 Graham's answer is correct. 格雷厄姆的答案是正确的。 But this might help someone with a similar problem. 但这可能会帮助遇到类似问题的人。 I thought you wanted to use the same variable to store a value and an array. 我以为您想使用相同的变量来存储值和数组。

首先将值转换为字符串(toString()),然后将其拆分(split()):

var arr = Latitude.toString().split('')

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

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