Javascript .JS/JQuery无法将整数推入数组
这是我目前掌握的代码:Javascript .JS/JQuery无法将整数推入数组,javascript,jquery,Javascript,Jquery,这是我目前掌握的代码: var purseValue = 10000; var storePerson = []; var storeAmount = []; $('#prompt').keypress(function() { // var whatMyUserTyped = $('#prompt').val(); //Input variable defined for future use. if (event.keyCode == 13)
var purseValue = 10000;
var storePerson = [];
var storeAmount = [];
$('#prompt').keypress(function() { //
var whatMyUserTyped = $('#prompt').val(); //Input variable defined for future use.
if (event.keyCode == 13) { //If enter is pressed,
if (whatMyUserTyped === 'purse'){ //If used types "purse"
$('#log li:last').text('ShylockBot pulls out his purse containing '+ purseValue+ ' ducat(s)');
} else { //log the phrase with total amount in purse.
var subtractValue = parseInt(whatMyUserTyped.match(/\d+/)); //scan for the number in my string, then turn into a number.
var arrayOfInput = whatMyUserTyped.split(" ");
purseValue = (purseValue - subtractValue); //purse money minus the above sum equals current amount in purse.
storePerson.push(arrayOfInput[1]);
storeAmount.push(); //I tried to use the "subtractValue" but for some reason didn't work. So I just selected from string again.
console.log(storePerson);
console.log(subtractValue);
我试图获得一个用户输入,我从中得到他们在字符串中输入的数字,然后我还得到他们的名字(考虑到短语是:“贷款人50美元”)
所以person将是arrayOfInput[1],number将是他们键入的任何数字
现在我尝试将这些值存储到2个数组中
我使用了.push(),它对“storePerson”很有效,每次我的函数运行时,它都会将输入的person添加到其中,但我无法将其添加到数组中。它只替换一个数字的数组,并且不存储旧值,这意味着将用storeAmount替换最新输入的值
尽管我是一个初学者,但我还是尽量说清楚。所以我希望有人能帮助我。谢谢。我读了很多遍,似乎你需要:
storeAmount.push(减去值[0]);
//感谢Orleaner指出match返回一个数组
你用的是双引号吗
PS:即使这样,这也不应该是个问题,每次添加字符串“subrtractValue:)要在jquery中将整数推入数组,它必须是
storeAmount.push(减去value.toString())
match
返回一个数组,而不是一个字符串。@Oleander是对的,那么WhatmyUserType.match(/\d+/)[0]
您是否忘记了将事件添加为函数参数$(“#prompt”)。按键(函数(事件)或它只是一个错误?这就是我要说的,为什么你要索引到subtractValue
,IIUC,它是一个数字:parseInt
的结果?也许[0]
应该附加到正在解析的match
调用的结果。