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

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

使用 SpeechSynthesisUtterance.voice 和 indow.speechSynthesis.getVoices() 将消息转换为语音。使用 window.speechSynthesis.speak() 播放消息。

了解有关Web Speech API的SpeechSynthesisUtterance接口的更多信息。

  1. const speak = message => {
  2. const msg = new SpeechSynthesisUtterance(message);
  3. msg.voice = window.speechSynthesis.getVoices()[0];
  4. window.speechSynthesis.speak(msg);
  5. };
  6. // speak('Hello, World') -> plays the message


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

使用 fs.writeFile(),模板字面量 和 JSON.stringify() 将 json 对象写入到 .json 文件中。

  1. const fs = require('fs');
  2. const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
  3. // jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'


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

使用 Array.reduce() 来创建和组合键值对。

  1. const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});
  2. // objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}


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

使用 Object.keys() 和 Array.map() 遍历对象的键并生成一个包含键值对的数组。

  1. const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
  2. // objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])


Shallow clone object (浅克隆对象)

使用 Object.assign() 和一个空对象({})来创建原始对象的浅拷贝。

  1. const shallowClone = obj => Object.assign({}, obj);
  2. /*
  3. const a = { x: true, y: 1 };
  4. const b = shallowClone(a);
  5. a === b -> false
  6. */



猜你喜欢

转载自blog.csdn.net/qq_26522773/article/details/79298550