您的位置:首页 > Web前端 > JavaScript

超实用的 JavaScript 其他(实验中)代码片段

2018-02-09 14:59 417 查看

Speech synthesis (语音合成,实验阶段)

使用 
SpeechSynthesisUtterance.voice
 和 
indow.speechSynthesis.getVoices()
 将消息转换为语音。使用 
window.speechSynthesis.speak()
 播放消息。了解有关Web Speech API的SpeechSynthesisUtterance接口的更多信息。const speak = message => {
const msg = new SpeechSynthesisUtterance(message);
msg.voice = window.speechSynthesis.getVoices()[0];
window.speechSynthesis.speak(msg);
};
// speak('Hello, World') -> plays the message

Write JSON to file (将 JSON 写到文件)

使用 
fs.writeFile()
,模板字面量 和 
JSON.stringify()
 将 
json
 对象写入到 
.json
 文件中。const fs = require('fs');
const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'

Object from key-value pairs (根据键值对创建对象)

使用 
Array.reduce()
 来创建和组合键值对。const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}

Object to key-value pairs (对象转化为键值对 )

使用 
Object.keys()
 和 
Array.map()
 遍历对象的键并生成一个包含键值对的数组。const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
// objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])

Shallow clone object (浅克隆对象)

使用 
Object.assign()
 和一个空对象(
{}
)来创建原始对象的浅拷贝。const shallowClone = obj => Object.assign({}, obj);
/*
const a = { x: true, y: 1 };
const b = shallowClone(a);
a === b -> false
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: