题目一:创建几个数组,随机选取数组中的变量,组合成句子,用+操作符连接

在存储随机变量时,遇到了点麻烦,感谢这篇文章的作者给了我思路:关于JavaScript中的随机数方法。并做了点笔记:随机数应用

全局变量在使用name时会出现问题,我改成了user

var user = ["Zhangsan","Lisi","Wangwu","Zhaoliu"];
var age = [12,34,33,55];
var job = ["Teacher","Doctor","Police","Driver"];

function b(start,end){                                        
    return Math.floor(Math.random()*(end-start) +start);        
}

var c = () => "I am " + user[b(0,user.length)] + ". I am " + age[b(0,age.length)] + " years old and I work as a " + job[b(0,job.length)] + "."

编辑器里,随机数可直接赋值给变量,控制台里不行:

var a = [];
var b = return Math.floor(Math.random()*a.length);

题目二:用join方法连接题目一中的句子。

var c = ["I am",user[b(0,user.length)],". I am",age[b(0,age.length)],"years old and I work as a",job[b(0,job.length)],"."].join(" ");

题目三:使用join方法把数组[3,2,1]转换成字符串"3 is bigger than 2 is bigger than 1!"?

var a = [3,2,1];
var b = [a[0],'is bigger than',a[1],'is bigger than',a[2],'!'].join(" ");

做题目中发现:
join()方法连接句子比用+操作符更简便,因为不需要考虑字符串与字符串之间连接符,放在括号中统一设置。


uccs
756 声望88 粉丝

3年 gis 开发,wx:ttxbg210604