1. 将let’s go home变为s’tel og emoh
var str = "let's go home";
/* s'tel og emoh */
/*
1.将字符串分割为数组split(" ")
["let's","go","home"]
*/
/* [[l,e,t,',s],[g,o],[h,o,m,e]] */
/* reverse */
/* [[s,',t,e,l],[o,g],[e,m,o,h]] */
/* join */
/* ["s'tel","og","emoh"] */
/* join */
/* s'tel og emoh */
map遍历
var arr = str.split(" ");
var newArr = arr.map(item=>{
return item.split("").reverse().join("")
})
console.log(newArr.join(" "))
forEach遍历
var arr = str.split(" ");
var all = []
arr.forEach(item=>{
let i = item.split("").reverse().join("")
all.push(i)
})
console.log(all.join(" "))
2. 筛选tian字音或者“天”开头的城市
var cities = [{spell:"tianmen",city:"天门"},{spell:"tianshui",city:"天水"},
{spell:"tianjin",city:"天津"},{spell:"wuhan",city:"武汉"},
{spell:"tianzifang",city:"田子坊"}]
var arr = []
cities.forEach((item,index)=>{
if(item.spell.startsWith("tian")||item.city.startsWith("天")){
arr.push(item.city)
}
}
)
console.log(arr)
//"天门""天水" "天津" "田子坊"
3. map()+join()
<script>
var obj = [{name:"汪峰",age:10},{name:"赵雷",age:5},{name:"房东的猫",age:6}]
/* 1.["汪峰","赵雷","房东的猫"] */
/* 2. 汪峰/赵雷/房东的猫*/
/* allName = "汪峰/赵雷/房东的猫" */
var newArr = obj.map(item=>{
return item.name
})
console.log(newArr.join("/"))
</script>
4. sum
<script>
var arr = [{price:4,count:2},{price:5,count:3},{price:6,count:3}];
function sum(arr){
var total = 0;
/* 8 23 41*/
arr.forEach(item=>{
total=item['price']*item['count']+total
})
return total;
}
console.log(sum(arr))
</script>