用文本替换整数

时间:2019-03-16 16:52:28

标签: javascript arrays

我有一个代码:

var number = 0;
var friends = ["Marta", "Anna", "Sara"];

number.replace("Marta", 0);
number.replace("Anna", 1);
number.replace("Sara", 2);

number = prompt("Hey! What Iker's friend do you want to see today?") - 1;

document.write(friends[number]);

我要用文字“ Marta”,“ Anna”和“ Sara”代替它们各自的编号。我知道我在这里设置的方法不正确。

任何人都有正确的密码吗?谢谢。

1 个答案:

答案 0 :(得分:2)

在尝试按索引访问值时,不需要替换

var friends = ["Marta", "Anna", "Sara"];

let number = prompt("Hey! What Iker's friend do you want to see today?") - 1;

document.write(friends[number] || 'Not in friends list :(');

而且Number也没有替换方法String具有


  

更新:我可以在提示()上替换一个字符串吗?像“玛塔”(Marta)到1?

var friendsArr = ["Marta", "Anna", "Sara"];
var friendsObj = {"Marta":1, "Anna":2, "Sara":3};

let input = prompt("Hey! What Iker's friend do you want to see today?")

let op = parseInt(input) ? friendsArr[input] : friendsObj[input] 

document.write(op || 'Not in friends list :(');