9.11云和恩墨笔试
算法题
- 给定两个数组,一个a一个b,b中元素不重复且均为a中元素,要求将a中元素,按照b的顺序排列,对于b没有的元素,则在a末尾按升序排列。
a = [2, 1, 4, 6, 3, 2, 4, 6, 5, 9],
b = [3, 2, 1, 4];
输出:[ 3, 2, 2, 1, 4, 4, 5, 6, 6, 9 ]
let a = [2, 1, 4, 6, 3, 2, 4, 6, 5, 9], b = [3, 2, 1, 4];
// [ 3, 2, 2, 1, 4, 4, 5, 6, 6, 9 ]
function sorttest(a,b) {
let newarr = [], non = [];
let map = new Map();
for (let i in b) {
map.set(b[i], 0);
}
for (let j in a) {
if (map.has(a[j])) {
map.set(a[j], map.get(a[j]) + 1);
} else {
non.push(a[j]);
}
}
for (let i of map) {
let num = i[0], cnt = i[1];
// console.log(i);
while (cnt > 0) {
newarr.push(num);
cnt--;
}
}
non.sort((a, b) => a - b);
return newarr.concat(non);
}
console.log(sorttest(a, b));//[ 3, 2, 2, 1, 4, 4, 5, 6, 6, 9 ]
- 本次答题中发现我对遍历map非常不熟练,但是可以确定一件事,map确实是有序的,按照读入的顺序。
- for i of map,这时的i是个[key,value]数组,还可以用map.keys()、map.values(),来分别遍历键值
正则表达式
盲点:正则表达式使用global运算符时,对lastIndex的影响
例子1
let reg = /a/g;
console.log(reg.test("a"), reg.test("aba"), reg.test("ababc"));
结果:true true false
着实震惊!!!去掉末尾的g之后:
例子2
let reg = /a/;
console.log(reg.test("a"), reg.test("aba"), reg.test("ababc"));
结果:true true true
可以看出是global运算符的作用,详细请参考 MDN:正则表达式使用global运算符时对lastIndex的影响
例子1是因为采用了g标识符
reg.test("a")//这时,匹配成功,test返回true,lastIndex=1
reg.test("aba") //从lastIndex=1处开始匹配,即查找ba中有无a,结果是true,导致lastIndex继续推进,lastIndex=3
reg.test("ababc") //从lastIndex=3处开始匹配,即查找bc中有无a,结果是false,lastIndex重新设为0
Using test() on a regex with the “global” flag
When a regex has the global flag set, test() will advance the lastIndex of the regex. (RegExp.prototype.exec() also advances the lastIndex property.)Further calls to test(str) will resume searching str starting from lastIndex. The lastIndex property will continue to increase each time
test() returns true.Note: As long as test() returns true, lastIndex will not reset—even when testing a different string!
When test() returns false, the calling regex’s lastIndex property will reset to 0.
mdn给出的例子:
const regex = /foo/g; // the "global" flag is set
// regex.lastIndex is at 0
regex.test('foo') // true
// regex.lastIndex is now at 3
regex.test('foo') // false
// regex.lastIndex is at 0
regex.test('barfoo') // true
// regex.lastIndex is at 6
regex.test('foobar') //false
// regex.lastIndex is at 0
// (...and so on)
隐式类型转换
- “5”-3 结果是2
- “5”-”3“ 结果是2