JavaScript 面试题

来源:互联网 发布:node.js 后端开发 编辑:程序博客网 时间:2024/06/06 01:21

转载自:

https://zhuanlan.zhihu.com/p/25308541

https://github.com/dwqs/blog/issues/17

你有必要知道的 25 个 JavaScript 面试题

1、使用 typeof bar === "object" 判断 bar 是不是一个对象有神马潜在的弊端?如何避免这种弊端?

使用 typeof 的弊端是显而易见的(这种弊端同使用 instanceof):

let obj = {};let arr = [];console.log(typeof obj === 'object');  //trueconsole.log(typeof arr === 'object');  //trueconsole.log(typeof null === 'object');  //true

从上面的输出结果可知,typeof bar === "object" 并不能准确判断 bar 就是一个 Object。可以通过Object.prototype.toString.call(bar) === "[object Object]" 来避免这种弊端:

let obj = {};let arr = [];console.log(Object.prototype.toString.call(obj));  //[object Object]console.log(Object.prototype.toString.call(arr));  //[object Array]console.log(Object.prototype.toString.call(null));  //[object Null]

另外,为了珍爱生命,请远离 ==
珍爱生命

[] === false 是返回 false 的。

2、下面的代码会在 console 输出神马?为什么?

(function(){  var a = b = 3;})();console.log("a defined? " + (typeof a !== 'undefined'));   console.log("b defined? " + (typeof b !== 'undefined'));

这跟变量作用域有关,输出换成下面的:

console.log(b); //3console,log(typeof a); //undefined

拆解一下自执行函数中的变量赋值:

b = 3;var a = b;

所以 b 成了全局变量,而 a 是自执行函数的一个局部变量。

3、下面的代码会在 console 输出神马?为什么?

var myObject = {    foo: "bar",    func: function() {        var self = this;        console.log("outer func:  this.foo = " + this.foo);        console.log("outer func:  self.foo = " + self.foo);        (function() {            console.log("inner func:  this.foo = " + this.foo);            console.log("inner func:  self.foo = " + self.foo);        }());    }};myObject.func();

第一个和第二个的输出不难判断,在 ES6 之前,JavaScript 只有函数作用域,所以 func 中的 IIFE 有自己的独立作用域,并且它能访问到外部作用域中的self,所以第三个输出会报错,因为 this 在可访问到的作用域内是 undefined,第四个输出是bar。如果你知道闭包,也很容易解决的:

(function(test) {            console.log("inner func:  this.foo = " + test.foo);  //'bar'            console.log("inner func:  self.foo = " + self.foo);}(self));

如果对闭包不熟悉,可以戳此:从作用域链谈闭包

4、将 JavaScript 代码包含在一个函数块中有神马意思呢?为什么要这么做?

换句话说,为什么要用立即执行函数表达式(Immediately-Invoked Function Expression)。

IIFE 有两个比较经典的使用场景,一是类似于在循环中定时输出数据项,二是类似于 JQuery/Node 的插件和模块开发。

for(var i = 0; i < 5; i++) {    setTimeout(function() {        console.log(i);      }, 1000);}

上面的输出并不是你以为的0,1,2,3,4,而输出的全部是5,这时 IIFE 就能有用了:

for(var i = 0; i < 5; i++) {    (function(i) {      setTimeout(function() {        console.log(i);        }, 1000);    })(i)}

而在 JQuery/Node 的插件和模块开发中,为避免变量污染,也是一个大大的 IIFE:

(function($) {         //代码 } )(jQuery);

5、在严格模式('use strict')下进行 JavaScript 开发有神马好处?

  • 消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为;
  • 消除代码运行的一些不安全之处,保证代码运行的安全;
  • 提高编译器效率,增加运行速度;
  • 为未来新版本的Javascript做好铺垫。

6、下面两个函数的返回值是一样的吗?为什么?

function foo1(){  return {      bar: "hello"  };}function foo2(){  return  {      bar: "hello"  };}

在编程语言中,基本都是使用分号(;)将语句分隔开,这可以增加代码的可读性和整洁性。而在JS中,如若语句各占独立一行,通常可以省略语句间的分号(;),JS 解析器会根据能否正常编译来决定是否自动填充分号:

var test = 1 + 2console.log(test);  //3

在上述情况下,为了正确解析代码,就不会自动填充分号了,但是对于 returnbreakcontinue 等语句,如果后面紧跟换行,解析器一定会自动在后面填充分号(;),所以上面的第二个函数就变成了这样:

function foo2(){  return;  {      bar: "hello"  };}

所以第二个函数是返回 undefined

7、神马是 NaN,它的类型是神马?怎么测试一个值是否等于 NaN?

NaN 是 Not a Number 的缩写,JavaScript 的一种特殊数值,其类型是 Number,可以通过 isNaN(param) 来判断一个值是否是 NaN

console.log(isNaN(NaN)); //trueconsole.log(isNaN(23)); //falseconsole.log(isNaN('ds')); //trueconsole.log(isNaN('32131sdasd')); //trueconsole.log(NaN === NaN); //falseconsole.log(NaN === undefined); //falseconsole.log(undefined === undefined); //falseconsole.log(typeof NaN); //numberconsole.log(Object.prototype.toString.call(NaN)); //[object Number]

ES6 中,isNaN() 成为了 Number 的静态方法:Number.isNaN().

8、解释一下下面代码的输出

console.log(0.1 + 0.2);   //0.30000000000000004console.log(0.1 + 0.2 == 0.3);  //false

JavaScript 中的 number 类型就是浮点型,JavaScript 中的浮点数采用IEEE-754 格式的规定,这是一种二进制表示法,可以精确地表示分数,比如1/2,1/8,1/1024,每个浮点数占64位。但是,二进制浮点数表示法并不能精确的表示类似0.1这样 的简单的数字,会有舍入误差。

由于采用二进制,JavaScript 也不能有限表示 1/10、1/2 等这样的分数。在二进制中,1/10(0.1)被表示为 0.00110011001100110011…… 注意0011 是无限重复的,这是舍入误差造成的,所以对于 0.1 + 0.2 这样的运算,操作数会先被转成二进制,然后再计算:

0.1 => 0.0001 1001 1001 1001…(无限循环)0.2 => 0.0011 0011 0011 0011…(无限循环)

双精度浮点数的小数部分最多支持 52 位,所以两者相加之后得到这么一串 0.0100110011001100110011001100110011001100...因浮点数小数位的限制而截断的二进制数字,这时候,再把它转换为十进制,就成了 0.30000000000000004。

对于保证浮点数计算的正确性,有两种常见方式。

一是先升幂再降幂:

function add(num1, num2){  let r1, r2, m;  r1 = (''+num1).split('.')[1].length;  r2 = (''+num2).split('.')[1].length;  m = Math.pow(10,Math.max(r1,r2));  return (num1 * m + num2 * m) / m;}console.log(add(0.1,0.2));   //0.3console.log(add(0.15,0.2256)); //0.3756

二是是使用内置的 toPrecision()toFixed() 方法,注意,方法的返回值字符串。

function add(x, y) {    return x.toPrecision() + y.toPrecision()}console.log(add(0.1,0.2));  //"0.10.2"

9、实现函数 isInteger(x) 来判断 x 是否是整数

可以将 x 转换成10进制,判断和本身是不是相等即可:

function isInteger(x) {     return parseInt(x, 10) === x; }

ES6 对数值进行了扩展,提供了静态方法 isInteger() 来判断参数是否是整数:

Number.isInteger(25) // trueNumber.isInteger(25.0) // trueNumber.isInteger(25.1) // falseNumber.isInteger("15") // falseNumber.isInteger(true) // false

JavaScript能够准确表示的整数范围在 -2^532^53 之间(不含两个端点),超过这个范围,无法精确表示这个值。ES6 引入了Number.MAX_SAFE_INTEGERNumber.MIN_SAFE_INTEGER这两个常量,用来表示这个范围的上下限,并提供了 Number.isSafeInteger() 来判断整数是否是安全型整数。

10、在下面的代码中,数字 1-4 会以什么顺序输出?为什么会这样输出?

(function() {    console.log(1);     setTimeout(function(){console.log(2)}, 1000);     setTimeout(function(){console.log(3)}, 0);     console.log(4);})();

这个就不多解释了,主要是 JavaScript 的定时机制和时间循环,不要忘了,JavaScript 是单线程的。详解可以参考 从setTimeout谈JavaScript运行机制。

11、写一个少于 80 字符的函数,判断一个字符串是不是回文字符串

function isPalindrome(str) {    str = str.replace(/\W/g, '').toLowerCase();    return (str == str.split('').reverse().join(''));}

这个题我在 codewars 上碰到过,并收录了一些不错的解决方式,可以戳这里:Palindrome For Your Dome

12、写一个按照下面方式调用都能正常工作的 sum 方法

console.log(sum(2,3));   // Outputs 5console.log(sum(2)(3));  // Outputs 5

针对这个题,可以判断参数个数来实现:

function sum() {  var fir = arguments[0];  if(arguments.length === 2) {    return arguments[0] + arguments[1]  } else {    return function(sec) {       return fir + sec;    }  }}

13、根据下面的代码片段回答后面的问题

for (var i = 0; i < 5; i++) {  var btn = document.createElement('button');  btn.appendChild(document.createTextNode('Button ' + i));  btn.addEventListener('click', function(){ console.log(i); });  document.body.appendChild(btn);}

1、点击 Button 4,会在控制台输出什么?
2、给出一种符合预期的实现方式

1、点击5个按钮中的任意一个,都是输出5
2、参考 IIFE。

14、下面的代码会输出什么?为什么?

var arr1 = "john".split(''); j o h nvar arr2 = arr1.reverse(); n h o jvar arr3 = "jones".split(''); j o n e sarr2.push(arr3);console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));

会输出什么呢?你运行下就知道了,可能会在你的意料之外。

MDN 上对于 reverse() 的描述是酱紫的:

Description
The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

reverse() 会改变数组本身,并返回原数组的引用。

slice 的用法请参考:slice

15、下面的代码会输出什么?为什么?

console.log(1 +  "2" + "2");console.log(1 +  +"2" + "2");console.log(1 +  -"1" + "2");console.log(+"1" +  "1" + "2");console.log( "A" - "B" + "2");console.log( "A" - "B" + 2);

输出什么,自己去运行吧,需要注意三个点:

  • 多个数字和数字字符串混合运算时,跟操作数的位置有关
console.log(2 + 1 + '3'); / /‘33’console.log('3' + 2 + 1); //'321'
  • 数字字符串之前存在数字中的正负号(+/-)时,会被转换成数字
console.log(typeof '3');   // stringconsole.log(typeof +'3');  //number

同样,可以在数字前添加 '',将数字转为字符串

console.log(typeof 3);   // numberconsole.log(typeof (''+3));  //string
  • 对于运算结果不能转换成数字的,将返回 NaN
console.log('a' * 'sd');   //NaNconsole.log('A' - 'B');  // NaN

这张图是运算转换的规则

运算符转换

16、如果 list 很大,下面的这段递归代码会造成堆栈溢出。如果在不改变递归模式的前提下修善这段代码?

var list = readHugeList();var nextListItem = function() {    var item = list.pop();    if (item) {        // process the list item...        nextListItem();    }};

原文上的解决方式是加个定时器:

var list = readHugeList();var nextListItem = function() {    var item = list.pop();    if (item) {        // process the list item...        setTimeout( nextListItem, 0);    }};

解决方式的原理请参考第10题。

17、什么是闭包?举例说明

可以参考此篇:从作用域链谈闭包

18、下面的代码会输出什么?为啥?

for (var i = 0; i < 5; i++) {  setTimeout(function() { console.log(i); }, i * 1000 );}

请往前面翻,参考第4题,解决方式已经在上面了

19、解释下列代码的输出

console.log("0 || 1 = "+(0 || 1));console.log("1 || 2 = "+(1 || 2));console.log("0 && 1 = "+(0 && 1));console.log("1 && 2 = "+(1 && 2));

逻辑与和逻辑或运算符会返回一个值,并且二者都是短路运算符:

  • 逻辑与返回第一个是 false 的操作数 或者 最后一个是 true的操作数
console.log(1 && 2 && 0);  //0console.log(1 && 0 && 1);  //0console.log(1 && 2 && 3);  //3

如果某个操作数为 false,则该操作数之后的操作数都不会被计算

  • 逻辑或返回第一个是 true 的操作数 或者 最后一个是 false的操作数
console.log(1 || 2 || 0); //1console.log(0 || 2 || 1); //2console.log(0 || 0 || false); //false

如果某个操作数为 true,则该操作数之后的操作数都不会被计算

如果逻辑与和逻辑或作混合运算,则逻辑与的优先级高:

console.log(1 && 2 || 0); //2console.log(0 || 2 && 1); //1console.log(0 && 2 || 1); //1

在 JavaScript,常见的 false 值:

0, '0', +0, -0, false, '',null,undefined,null,NaN

要注意空数组([])空对象({}):

console.log([] == false) //trueconsole.log({} == false) //falseconsole.log(Boolean([])) //trueconsole.log(Boolean({})) //true

所以在 if 中,[]{} 都表现为 true

if

20、解释下面代码的输出

console.log(false == '0')console.log(false === '0')

请参考前面第14题运算符转换规则的图。

21、解释下面代码的输出

var a={},    b={key:'b'},    c={key:'c'};a[b]=123;a[c]=456;console.log(a[b]);

输出是 456,参考原文的解释:

The reason for this is as follows: When setting an object property, JavaScript will implicitly stringify the parameter value. In this case, since b and c are both objects, they will both be converted to "[object Object]". As a result, a[b] anda[c] are both equivalent to a["[object Object]"] and can be used interchangeably. Therefore, setting or referencing a[c] is precisely the same as setting or referencing a[b].

22、解释下面代码的输出

console.log((function f(n){return ((n > 1) ? n * f(n-1) : n)})(10));

结果是10的阶乘。这是一个递归调用,为了简化,我初始化 n=5,则调用链和返回链如下:

递归

23、解释下面代码的输出

(function(x) {    return (function(y) {        console.log(x);    })(2)})(1);

输出1,闭包能够访问外部作用域的变量或参数。

24、解释下面代码的输出,并修复存在的问题

var hero = {    _name: 'John Doe',    getSecretIdentity: function (){        return this._name;    }};var stoleSecretIdentity = hero.getSecretIdentity;console.log(stoleSecretIdentity());console.log(hero.getSecretIdentity());

getSecretIdentity 赋给 stoleSecretIdentity,等价于定义了 stoleSecretIdentity 函数:

var stoleSecretIdentity =  function (){        return this._name;}

stoleSecretIdentity 的上下文是全局环境,所以第一个输出 undefined。若要输出John Doe,则要通过 callapplybind 等方式改变stoleSecretIdentitythis 指向(hero)。

第二个是调用对象的方法,输出 John Doe

25、给你一个 DOM 元素,创建一个能访问该元素所有子元素的函数,并且要将每个子元素传递给指定的回调函数。

函数接受两个参数:

  • DOM
  • 指定的回调函数

原文利用 深度优先搜索(Depth-First-Search) 给了一个实现:

function Traverse(p_element,p_callback) {   p_callback(p_element);   var list = p_element.children;   for (var i = 0; i < list.length; i++) {       Traverse(list[i],p_callback);  // recursive call   }}

文章参考:

25 Essential JavaScript Interview Questions
JavaScript中的立即执行函数表达式
Javascript 严格模式详解

=================================================================================

JavaScript 面试中常见算法问题详解

JavaScript 面试中常见算法问题详解 翻译自Interview Algorithm Questions in Javascript() {...} 从属于笔者的 Web 前端入门与工程实践。下文提到的很多问题从算法角度并不一定要么困难,不过用 JavaScript 内置的 API 来完成还是需要一番考量的。

JavaScript Specification

阐述下 JavaScript 中的变量提升

所谓提升,顾名思义即是 JavaScript 会将所有的声明提升到当前作用域的顶部。这也就意味着我们可以在某个变量声明前就使用该变量,不过虽然 JavaScript 会将声明提升到顶部,但是并不会执行真的初始化过程。

阐述下 use strict; 的作用

use strict; 顾名思义也就是 JavaScript 会在所谓严格模式下执行,其一个主要的优势在于能够强制开发者避免使用未声明的变量。对于老版本的浏览器或者执行引擎则会自动忽略该指令。

// Example of strict mode"use strict";catchThemAll();function catchThemAll() {  x = 3.14; // Error will be thrown  return x * x;}

解释下什么是 Event Bubbling 以及如何避免

Event Bubbling 即指某个事件不仅会触发当前元素,还会以嵌套顺序传递到父元素中。直观而言就是对于某个子元素的点击事件同样会被父元素的点击事件处理器捕获。避免 Event Bubbling 的方式可以使用event.stopPropagation() 或者 IE 9 以下使用event.cancelBubble。

== 与 === 的区别是什么

=== 也就是所谓的严格比较,关键的区别在于=== 会同时比较类型与值,而不是仅比较值。

// Example of comparators0 == false; // true0 === false; // false2 == '2'; // true2 === '2'; // false

解释下 null 与 undefined 的区别

JavaScript 中,null 是一个可以被分配的值,设置为 null 的变量意味着其无值。而 undefined 则代表着某个变量虽然声明了但是尚未进行过任何赋值。

解释下 Prototypal Inheritance 与 Classical Inheritance 的区别

在类继承中,类是不可变的,不同的语言中对于多继承的支持也不一样,有些语言中还支持接口、final、abstract 的概念。而原型继承则更为灵活,原型本身是可以可变的,并且对象可能继承自多个原型。

数组

找出整型数组中乘积最大的三个数

给定一个包含整数的无序数组,要求找出乘积最大的三个数。

var unsorted_array = [-10, 7, 29, 30, 5, -10, -70];computeProduct(unsorted_array); // 21000function sortIntegers(a, b) {  return a - b;}// greatest product is either (min1 * min2 * max1 || max1 * max2 * max3)function computeProduct(unsorted) {  var sorted_array = unsorted.sort(sortIntegers),    product1 = 1,    product2 = 1,    array_n_element = sorted_array.length - 1;  // Get the product of three largest integers in sorted array  for (var x = array_n_element; x > array_n_element - 3; x--) {      product1 = product1 * sorted_array[x];  }  product2 = sorted_array[0] * sorted_array[1] * sorted_array[array_n_element];  if (product1 > product2) return product1;  return product2};

寻找连续数组中的缺失数

给定某无序数组,其包含了 n 个连续数字中的 n - 1 个,已知上下边界,要求以O(n)的复杂度找出缺失的数字。

// The output of the function should be 8var array_of_integers = [2, 5, 1, 4, 9, 6, 3, 7];var upper_bound = 9;var lower_bound = 1;findMissingNumber(array_of_integers, upper_bound, lower_bound); //8function findMissingNumber(array_of_integers, upper_bound, lower_bound) {  // Iterate through array to find the sum of the numbers  var sum_of_integers = 0;  for (var i = 0; i < array_of_integers.length; i++) {    sum_of_integers += array_of_integers[i];  }  // 以高斯求和公式计算理论上的数组和  // Formula: [(N * (N + 1)) / 2] - [(M * (M - 1)) / 2];  // N is the upper bound and M is the lower bound  upper_limit_sum = (upper_bound * (upper_bound + 1)) / 2;  lower_limit_sum = (lower_bound * (lower_bound - 1)) / 2;  theoretical_sum = upper_limit_sum - lower_limit_sum;  //  return (theoretical_sum - sum_of_integers)}

数组去重

给定某无序数组,要求去除数组中的重复数字并且返回新的无重复数组。

// ES6 Implementationvar array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];Array.from(new Set(array)); // [1, 2, 3, 5, 9, 8]// ES5 Implementationvar array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];uniqueArray(array); // [1, 2, 3, 5, 9, 8]function uniqueArray(array) {  var hashmap = {};  var unique = [];  for(var i = 0; i < array.length; i++) {    // If key returns null (unique), it is evaluated as false.    if(!hashmap.hasOwnProperty([array[i]])) {      hashmap[array[i]] = 1;      unique.push(array[i]);    }  }  return unique;}

数组中元素最大差值计算

给定某无序数组,求取任意两个元素之间的最大差值,注意,这里要求差值计算中较小的元素下标必须小于较大元素的下标。譬如[7, 8, 4, 9, 9, 15, 3, 1, 10]这个数组的计算值是 11( 15 - 4 ) 而不是 14(15 - 1),因为 15 的下标小于 1。

var array = [7, 8, 4, 9, 9, 15, 3, 1, 10];// [7, 8, 4, 9, 9, 15, 3, 1, 10] would return `11` based on the difference between `4` and `15`// Notice: It is not `14` from the difference between `15` and `1` because 15 comes before 1.findLargestDifference(array);function findLargestDifference(array) {  // 如果数组仅有一个元素,则直接返回 -1  if (array.length <= 1) return -1;  // current_min 指向当前的最小值  var current_min = array[0];  var current_max_difference = 0;    // 遍历整个数组以求取当前最大差值,如果发现某个最大差值,则将新的值覆盖 current_max_difference  // 同时也会追踪当前数组中的最小值,从而保证 `largest value in future` - `smallest value before it`  for (var i = 1; i < array.length; i++) {    if (array[i] > current_min && (array[i] - current_min > current_max_difference)) {      current_max_difference = array[i] - current_min;    } else if (array[i] <= current_min) {      current_min = array[i];    }  }  // If negative or 0, there is no largest difference  if (current_max_difference <= 0) return -1;  return current_max_difference;}

数组中元素乘积

给定某无序数组,要求返回新数组 output ,其中 output[i] 为原数组中除了下标为 i 的元素之外的元素乘积,要求以 O(n) 复杂度实现:

var firstArray = [2, 2, 4, 1];var secondArray = [0, 0, 0, 2];var thirdArray = [-2, -2, -3, 2];productExceptSelf(firstArray); // [8, 8, 4, 16]productExceptSelf(secondArray); // [0, 0, 0, 0]productExceptSelf(thirdArray); // [12, 12, 8, -12]function productExceptSelf(numArray) {  var product = 1;  var size = numArray.length;  var output = [];  // From first array: [1, 2, 4, 16]  // The last number in this case is already in the right spot (allows for us)  // to just multiply by 1 in the next step.  // This step essentially gets the product to the left of the index at index + 1  for (var x = 0; x < size; x++) {      output.push(product);      product = product * numArray[x];  }  // From the back, we multiply the current output element (which represents the product  // on the left of the index, and multiplies it by the product on the right of the element)  var product = 1;  for (var i = size - 1; i > -1; i--) {      output[i] = output[i] * product;      product = product * numArray[i];  }  return output;}

数组交集

给定两个数组,要求求出两个数组的交集,注意,交集中的元素应该是唯一的。

var firstArray = [2, 2, 4, 1];var secondArray = [1, 2, 0, 2];intersection(firstArray, secondArray); // [2, 1]function intersection(firstArray, secondArray) {  // The logic here is to create a hashmap with the elements of the firstArray as the keys.  // After that, you can use the hashmap's O(1) look up time to check if the element exists in the hash  // If it does exist, add that element to the new array.  var hashmap = {};  var intersectionArray = [];  firstArray.forEach(function(element) {    hashmap[element] = 1;  });  // Since we only want to push unique elements in our case... we can implement a counter to keep track of what we already added  secondArray.forEach(function(element) {    if (hashmap[element] === 1) {      intersectionArray.push(element);      hashmap[element]++;    }  });  return intersectionArray;  // Time complexity O(n), Space complexity O(n)}

字符串

颠倒字符串

给定某个字符串,要求将其中单词倒转之后然后输出,譬如"Welcome to this Javascript Guide!" 应该输出为 "emocleW ot siht tpircsavaJ !ediuG"。

var string = "Welcome to this Javascript Guide!";// Output becomes !ediuG tpircsavaJ siht ot emocleWvar reverseEntireSentence = reverseBySeparator(string, "");// Output becomes emocleW ot siht tpircsavaJ !ediuGvar reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");function reverseBySeparator(string, separator) {  return string.split(separator).reverse().join(separator);}

乱序同字母字符串

给定两个字符串,判断是否颠倒字母而成的字符串,譬如Mary与Army就是同字母而顺序颠倒:

var firstWord = "Mary";var secondWord = "Army";isAnagram(firstWord, secondWord); // truefunction isAnagram(first, second) {  // For case insensitivity, change both words to lowercase.  var a = first.toLowerCase();  var b = second.toLowerCase();  // Sort the strings, and join the resulting array to a string. Compare the results  a = a.split("").sort().join("");  b = b.split("").sort().join("");  return a === b;}

会问字符串

判断某个字符串是否为回文字符串,譬如racecar与race car都是回文字符串:

isPalindrome("racecar"); // trueisPalindrome("race Car"); // truefunction isPalindrome(word) {  // Replace all non-letter chars with "" and change to lowercase  var lettersOnly = word.toLowerCase().replace(/\s/g, "");  // Compare the string with the reversed version of the string  return lettersOnly === lettersOnly.split("").reverse().join("");}

栈与队列

使用两个栈实现入队与出队

var inputStack = []; // First stackvar outputStack = []; // Second stack// For enqueue, just push the item into the first stackfunction enqueue(stackInput, item) {  return stackInput.push(item);}function dequeue(stackInput, stackOutput) {  // Reverse the stack such that the first element of the output stack is the  // last element of the input stack. After that, pop the top of the output to  // get the first element that was ever pushed into the input stack  if (stackOutput.length <= 0) {    while(stackInput.length > 0) {      var elementToOutput = stackInput.pop();      stackOutput.push(elementToOutput);    }  }  return stackOutput.pop();}

判断大括号是否闭合

创建一个函数来判断给定的表达式中的大括号是否闭合:

var expression = "{{}}{}{}"var expressionFalse = "{}{{}";isBalanced(expression); // trueisBalanced(expressionFalse); // falseisBalanced(""); // truefunction isBalanced(expression) {  var checkString = expression;  var stack = [];  // If empty, parentheses are technically balanced  if (checkString.length <= 0) return true;  for (var i = 0; i < checkString.length; i++) {    if(checkString[i] === '{') {      stack.push(checkString[i]);    } else if (checkString[i] === '}') {      // Pop on an empty array is undefined      if (stack.length > 0) {        stack.pop();      } else {        return false;      }    }  }  // If the array is not empty, it is not balanced  if (stack.pop()) return false;  return true;}

递归

二进制转换

通过某个递归函数将输入的数字转化为二进制字符串:

decimalToBinary(3); // 11decimalToBinary(8); // 1000decimalToBinary(1000); // 1111101000function decimalToBinary(digit) {  if(digit >= 1) {    // If digit is not divisible by 2 then recursively return proceeding    // binary of the digit minus 1, 1 is added for the leftover 1 digit    if (digit % 2) {      return decimalToBinary((digit - 1) / 2) + 1;    } else {      // Recursively return proceeding binary digits      return decimalToBinary(digit / 2) + 0;    }  } else {    // Exit condition    return '';  }}

二分搜索

function recursiveBinarySearch(array, value, leftPosition, rightPosition) {  // Value DNE  if (leftPosition > rightPosition) return -1;  var middlePivot = Math.floor((leftPosition + rightPosition) / 2);  if (array[middlePivot] === value) {    return middlePivot;  } else if (array[middlePivot] > value) {    return recursiveBinarySearch(array, value, leftPosition, middlePivot - 1);  } else {    return recursiveBinarySearch(array, value, middlePivot + 1, rightPosition);  }}

数字

判断是否为 2 的指数值

isPowerOfTwo(4); // trueisPowerOfTwo(64); // trueisPowerOfTwo(1); // trueisPowerOfTwo(0); // falseisPowerOfTwo(-1); // false// For the non-zero case:function isPowerOfTwo(number) {  // `&` uses the bitwise n.  // In the case of number = 4; the expression would be identical to:  // `return (4 & 3 === 0)`  // In bitwise, 4 is 100, and 3 is 011. Using &, if two values at the same  // spot is 1, then result is 1, else 0. In this case, it would return 000,  // and thus, 4 satisfies are expression.  // In turn, if the expression is `return (5 & 4 === 0)`, it would be false  // since it returns 101 & 100 = 100 (NOT === 0)  return number & (number - 1) === 0;}// For zero-case:function isPowerOfTwoZeroCase(number) {  return (number !== 0) && ((number & (number - 1)) === 0);}

0 0