我创建了一个对象并提示用户输入值(用逗号除以)但是如何显示某个值而不是整个字符串?
这是我的代码:
var obj = {
name: "",
colors: [] };
obj = prompt("Enter your name and favorite colors (separated by comma).”.split(‘,’));
alert(obj.name + "' favorite colors are " obj.colors);
答案 0 :(得分:1)
当您使用.split()
时,您将获得一个数组。要使用它,你应该这样做:
obj[0]
和obj[1]
,希望用户先添加名称而不是先着色...
如果您不想使用2个不同的问题/承诺,您应该这样做:
var obj = {};
var parts = prompt("Enter your name and favorite colors (separated by comma).").split(' ').join('').split(',');
obj.name = parts.shift();
console.log(parts)
obj.colors = parts;
alert(obj.name + "'s favorite colors are " + obj.colors.join(', '));
答案 1 :(得分:0)
var obj = {
name: "",
colors: []
};
obj.name = prompt("Enter your name");
obj.colors = new Array(prompt("and favorite colors (separated by comma)."));
alert(obj.name + "'s favorite colors are " +obj.colors);