简体   繁体   English

如何将特定字符串转换为数组中的特定数字?

[英]How do I convert specific strings into specific number in an array?

I'm looking for a way to convert a string to a number.我正在寻找一种将字符串转换为数字的方法。 I'm making a rock paper scissors game for class, and I am not allowed to use custom functions.我正在为班级制作剪刀石头布游戏,并且不允许使用自定义功能。 I want to convert the variable userChoice from "rock", "paper", and "scissors" to 0, 1, and 2, respectively.我想将变量 userChoice 从“rock”、“paper”和“scissors”分别转换为 0、1 和 2。 Here's the code in question:这是有问题的代码:

    const options = [`rock`, `paper`, `scissors`];
    alert (`Let's play Rock, Paper, Scissors!`);
    let userChoice =  prompt (`Please enter your choice (rock, paper, or scissors`);
    let compChoice =  Math.floor((Math.random() * 3));
    let inputValid = null

if ((userChoice == `rock`) || (userChoice == `paper`) || (userChoice == `scissors`)) {
inputValid = true
}

else {
  inputValid = false
}

if (( userChoice )


    
    let dialogChoice = (`You chose ${userChoice}! The computer chose ${compChoice}!`)

let dialogUserWin = `User wins!`
let dialogCompWin = `Computer wins!`
let dialogTie     = `It's a tie!`
let dialogReplay = `Press F5 to play again`

console.log(compChoice)

//I could always do something like:

if (userChoice = `rock`) {
userChoice = 0}
else if (userChoice = `rock`) {
userChoice = 1}
else if (userChoice = `rock`) {
userChoice = 2}

//but that seems dreadfully inelegant

Here are 2 options to achieve what u want.这里有 2 个选项来实现你想要的。 (If I understood correctly) (如果我理解正确)

let a = ["a1","a2", "a3"]

let input = "a2"

// option 1 (I don't know if you are allowed to use indexOf)
let input_to_number = a.indexOf(input)

console.log(input_to_number)

// option 2 (This is a little bit more elegant and generic than putting if else for every option)
let answear = -1
for(let i=0; i<a.length; i++){
    if(input === a[i]){
        answear = i
        break;
    }
}

console.log(answear) 

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

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