前端面试题2

1、下面程序的执行结果是什么?请分析原因?
function f({ x = 10 } = {}, { y } = { y: 10 }) {
    console.log( x + " " + y +"\n");
}

根据es6提供的参数值默认原理,undefined就是空。得到以下值。
f(); // 10 10  
f( undefined, undefined ); // 10 10  
f( {}, undefined ); // 10 10  
f( {}, {} ); // 10 undefined  
f( undefined, {} ); // 10 undefined  
f( { x: 2 }, { y: 3 } ); // 2 3

        2.Array.from方法的作用是什么?
将类数组转化为数组。
        3.Array.of和使用Array()或new Array()构建数组实例有什么区别
Array.of()是对new Array()的扩展 。不论输入什么,都代表的是数组元素。
        4.下面程序执行结果是什么?
function push(array, ...items) {
       items.forEach(function(item) {
             array.push(item);
             console.log(item);
       });
}
var a = [1,2];
push(a, 1, 2, 3)

123

5.下面程序执行结果是什么?
const headAndTail = (head, ...tail) => [head, tail];

headAndTail(6, 2, 3, 4, 5)

6[2345]

6.node是什么?
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。

7.编写程序使用ES6定义 Person类,包括类实例属性(name,age),实例方法say()该方法
返回name和age字符串

class Person{
                constructor(name,age){
                    this.name=name;
                    this.age=age
                }
                say(){
                    return '我的名字是'+this.name+'我的年龄是:'+this.age;
                }
            }

     var p=new Person('小明',12);
            console.log(p.say());

 8..下面程序执行结果为: 
 var p=new Person();
  console.log(p.__proto__===Person.prototype)

// 实例对象的__proto__指向的是构造函数的prototype
            console.log(p.__proto__==Person.prototype);

结果为true。

9.下面程序正确吗?错在哪里?如何改正?
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}
class ColorPoint extends Point {
          constructor(x, y, color) {
    this.color = color; // ReferenceError
    super(x, y);
           }
}
var cp=new ColorPoint(10,20,'red');

子类的this关键字根据super方法创建

应改为constructor(x,y,color){

super(x,y,color);

this.color=color;

}

10.下面程序执行结果为?
class Parent {
  static myMethod(msg) {
    console.log('static', msg);
  }
  myMethod(msg) {
    console.log('instance', msg);
  }
}
class Child extends Parent {
  static myMethod(msg) {
    super.myMethod(msg);
  }
  myMethod(msg) {
    super.myMethod(msg);
  }
}
Child.myMethod(1); 
var child = new Child();
child.myMethod(2); 

结果为 static1,instance2。

11.请利用class重新定义Cat,并让它从已有的Animal继承,然后新增一个方法say(),
返回字符串'Hello, xxx!'
class Animal {
    constructor(name) {
        this.name = name;
    }
}

 
  1. class Animal {

  2. constructor(name) {

  3. this.name = name;

  4. }

  5. }

  6. class Cat extends Animal{

  7. constructor(name){

  8. super(name);

  9. }

  10. say(){

  11. return 'hello xxxx!';

  12. }

  13. }

12.接上面程序分析下面代码执行结果为
var kitty = new Cat('Kitty');
var doraemon = new Cat('哆啦A梦');
if ((new Cat('x') instanceof Animal) && kitty && kitty.name === 'Kitty' && kitty.say &&
 typeof kitty.say === 'function' && kitty.say() === 'Hello,Kitty!'  && 
kitty.say === doraemon.say) {
         console.log('测试通过!');
} else {
        console.log('测试失败!');
}

结果为测试失败。

原因为kitty.say() === 'Hello,Kitty!'与say()方法的输出不符应该为hello xxxx。

13.下面程序执行结果为
(typeof (new (class { class () {} })));

结果为objiect。在有new的时候都是一个实例对象。

2、node 和 java/php区别?

这三总语言最明显的区别也是最基本的区别就是,Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。而java和php是一个编程语言。

node相对于java而言相对于大项目java更容易管理不容易出错。而node的优势就是开发快,运算效率高,但是node运用的是js的开发语言,需要运行时才会知道哪里出了问题,java不会他会及时的给予开发者错误反馈。

而node相对于php而言就是一下几种区别:

1、性能方面:

由于 Node.js 遵循事件驱动的非阻塞I/O模型,与传统的后端技术相比,Node.js 能够处理大量的服务器请求。PHP 遵循一个阻塞模型,其中在服务器端创建多个线程来处理多个客户端请求,如果代码没有被优化,它会导致高服务器负载和响应时间。

2、托管和部署:

PHP 应用程序可以在包括 Nginx 和 Apache 以及 Windows 和 Linux 平台在内的任何服务器上运行,这使得部署过程变得更容易。

而 Node.js,则需要具有 SSH 访问权限的虚拟服务器。因此,在没有任何控制台命令和 Secure Shell(SSH)知识的情况下,用 PHP 部署小型企业和个人应用会更好。

3、外部依赖:

Node.js 依赖关系较少,用几行代码就可以设置一个 Web 服务器。但运行 PHP 应用程序,就需要外部服务器软件。用 Node.js 的开发人员只需要 NPM(节点包管理器)就可以下载 Node 模块,这些模块可以轻松地集成到应用程序中,提供额外的功能。

4、CPU 扩展任务:

Node.js 可能在高吞吐量方面表现优异,但是当应用程序繁重,需要 CPU 做大量工作时,Node.js 肯定会有所欠缺。在这种情况下,PHP 最适合做 Web 应用程序的后端。

5、单页应用程序:

如果您使用过 Gmail,那么您可能知道什么是单页应用程序(Single Page Application)。Web 应用程序在初始客户端请求时加载,之后根据客户端请求刷新的网页的特定部分。Node.js 与 AngularJS 的联合是开发单页应用程序的完美方案。

6、开发环境:

Node.js 可以用于桌面应用程序开发(Windows,Linux和Mac),移动应用程序开发(混合和跨平台应用程序),甚至构建基于控制台的应用程序。虽然有一些也可以使用 PHP 来开发,但是大多数开发人员不会这样做。

7、社区支持:

由于 PHP 比 Node.js 早诞生将近20年,所以在文档,API 和代码库等在线资源方面更为丰富。所以很有可能其他人也尝试了你想要用代码完成的事情并从中获得了帮助。

另一方面,Node.js 虽然已经得到了开发者和组织的广泛关注,但是它支持开发者开发的资源缺相当少。

Node.js 和 PHP是相辅相成的,因为这两种技术都有各自的优点和缺点。这大多是相似的情况在比较或选择用于Web,桌面和移动开发的其他技术时。Node.js有前途,并且肯定会占据PHP市场的一部分,但是不能完全取代 PHP。

同步和异步区别?

同步:

所有的操作都做完,才返回给用户。这样用户在线等待的时间太长,给用户一种卡死了的感觉(就是系统迁移中,点击了迁移,界面就不动了,但是程序还在执行,卡死了的感觉)。这种情况下,用户不能关闭界面,如果关闭了,即迁移程序就中断了。

异步:
将用户请求放入消息队列,并反馈给用户,系统迁移程序已经启动,你可以关闭浏览器了。然后程序再慢慢地去写入数据库去。这就是异步。但是用户没有卡死的感觉,会告诉你,你的请求系统已经响应了。你可以关闭界面了。

同步,是所有的操作都做完,才返回给用户结果。即写完数据库之后,再响应用户,用户体验不好。
异步,不用等所有操作都做完,就相应用户请求。即先响应用户请求,然后慢慢去写数据库,用户体验较好。

异步操作例子

为了避免短时间大量的数据库操作,就使用缓存机制,也就是消息队列。先将数据放入消息队列,然后再慢慢写入数据库。

引入消息队列机制,虽然可以保证用户请求的快速响应,但是并没有使得我数据迁移的时间变短(即80万条数据写入mysql需要1个小时,用了redis之后,还是需要1个小时,只是保证用户的请求的快速响应。用户输入完http url请求之后,就可以把浏览器关闭了,干别的去了。如果不用redis,浏览器不能关闭)。

同步就没有任何价值了吗?

比如网站的登录效果,银行的转账等等都需要同步的操作。

判断文件夹下文件状态

 
  1. const fs=require('fs');

  2. fs.readdir(__dirname,(err,files)=>{

  3. if(err) throw err;

  4. console.log(files);

  5. for(let i=0;i<files.length;i++){

  6. fs.stat(__dirname+'/'+files[i],(err,stats)=>{

  7. if(stats.isFile()){

  8. console.log(files[i]+'是一个文件')

  9. }else{

  10. console.log(files[i]+'是一个文件')

  11. }

  12. })

  13. }

  14. });

登录和注册功能?登录使用get请求 注册使用post请求 请求的路径都是submit前端两个页面,后台只有一个js文件

html 代码(get请求):

 
  1. <!DOCTYPE html>

  2. <html>

  3. <head>

  4. <meta charset="utf-8">

  5. <title></title>

  6. </head>

  7. <body>

  8. <form class="mui-input-group" action="http://localhost:8989/submit/" method="get">

  9. <div class="mui-input-row">

  10. <label>注册</label>

  11. <input type="text" class="mui-input-clear" placeholder="用户名" name="user">

  12. <input type="password" class="mui-input-clear" placeholder="密码" name="pass">

  13. <input type="submit"/>

  14. <a href="index2.html">登录</a>

  15. </div>

  16. </body>

  17. </html>

html(post请求):

 
  1. <html>

  2. <head>

  3. <meta charset="utf-8">

  4. <title></title>

  5. </head>

  6. <body>

  7. <form class="mui-input-group" action="http://localhost:8989/submit/" method="post">

  8. <div class="mui-input-row">

  9. <label>登录</label>

  10. <input type="text" class="mui-input-clear" placeholder="用户名" name="user">

  11. <input type="password" class="mui-input-clear" placeholder="密码" name="pass">

  12. <input type="submit"/>

  13. <a href="index.html">注册</a>

  14. </div>

  15. </form>

  16. </body>

  17. </html>

js代码:

 
  1. const http=require('http');

  2. const fs=require('fs');

  3. const path=require('path');

  4. const readfile=require('readfile');

  5. const url=require('url');

  6. const querystring=require('querystring');

  7. let server=http.createServer((req,res)=>{

  8. if(req.url=='/favicon.ico') return;

  9. if(req.url.startsWith('/form')){

  10. readfile(__dirname,req,res);

  11. }else if(req.url.startsWith('/submit')){

  12. if(url.parse(req.url,true).query=={}){

  13. let params=url.parse(req.url,true).query;

  14. res.writeHead(200,{'Content-type':'text/plain;charset=utf-8'});

  15. res.end(`用户名${params.user}密码是${params.pass}`);

  16. }

  17. else{

  18. var allData='';

  19. req.on('data',(chunk)=>{

  20. allData+=chunk;

  21. });

  22. req.on('end',()=>{

  23. console.log(querystring.parse(allData));

  24. let a=querystring.parse(allData);

  25. res.writeHead(200,{'Content-type':'text/plain;charset=utf-8'});

  26. res.end(`用户名${a.user}密码是${a.pass}`);

  27. });

  28. }

  29. }else{

  30. res.end('404');

  31. }

  32. });

  33. server.listen('8989');

使用express来实现上述代码

html(get):

 
  1. <!DOCTYPE html>

  2. <html>

  3. <head>

  4. <meta charset="utf-8">

  5. <title></title>

  6. <script src="../../public/js/jquery-3.0.0.min.js"></script>

  7. </head>

  8. <body>

  9. <h1>登录页面</h1>

  10. <input type="text" placeholder="用户名" name="uesr" />

  11. <span></span>

  12. <br><br>

  13. <input type="password" placeholder="密码" name="pass" />

  14. <button type="button">登录</button>

  15. <a href="index2.html">注册账号</a>

  16. </body>

  17. <script>

  18. $('button').click(()=>{

  19. $.ajax({

  20. url:'http://localhost:8989/submit',

  21. method:'get',

  22. data:{

  23. user:$('input[type="text"]').val(),

  24. pass:$('input[type="password"]').val()

  25. },

  26. success:function(res){

  27. if(res=='lp'){

  28. $('span').html('该用户名存在请重新输入');

  29. }else{

  30. $('span').html('√');

  31. location.href='app.html';

  32. }

  33. }

  34. })

  35. })

  36.  
  37. </script>

  38. </html>

html(post):

 
  1. <!DOCTYPE html>

  2. <html>

  3. <head>

  4. <meta charset="utf-8">

  5. <title></title>

  6. <script type="text/javascript" src="../../public/js/jquery-3.0.0.min.js"></script>

  7. </head>

  8. <body>

  9. <h1>注册页面</h1>

  10. <input type="text" placeholder="用户名" name="uesr" />

  11. <span></span>

  12. <br><br>

  13. <input type="password" placeholder="密码" name="pass" />

  14. <button type="button">注册</button>

  15. <a href="index2.html">登录账号</a>

  16. </body>

  17. <script>

  18. $('button').click(()=>{

  19. $.ajax({

  20. method:'post',

  21. url:'http:localhost:8989/submit',

  22. data:{

  23. user:$('input[type="text"]').val(),

  24. pass:$('input[type="password"]').val()

  25. },

  26. success:(res)=>{

  27. if(res=='lp'){

  28. $('span').html('该用户名存在请重新输入');

  29. }else{

  30. $('span').html('√');

  31. location.href='app.html';

  32. }

  33. }

  34. })

  35. })

  36. </script>

  37. </html>

express模块代码:

 
  1. const express=require('express');

  2. const app=express();

  3. var bodyParser=require('body-parser');

  4. var urlencodedParser=bodyParser.urlencoded({extended:false});

  5. app.use('/',express.static('./www/form'));

  6. app.use('/public',express.static('./public'));

  7. app.post('/submit',urlencodedParser,(req,res)=>{

  8. res.send(req.body);

  9. });

  10. app.get('/submit',(req,res)=>{

  11. res.send(`${req.query.user}`)

  12. });

  13. app.listen('8989');

关系型数据库有哪些,非关系型数据库有哪些?两者区别?

1、数据存储方式不同。

关系型和非关系型数据库的主要差异是数据存储的方式。关系型数据天然就是表格式的bai,因此存储在数据表的行和列中。数据表可以彼此关联协作存储,也很容易提取数据。

与其相反,非关系型数据不适合存储在数据表的行和列中,而是大块组合在一起。非关系型数据通常存储在数据集中,就像文档、键值对或者图结构。你的数据及其特性是选择数据存储和提取方式的首要影响因素。

2、扩展方式不同。

SQL和NoSQL数据库最大的差别可能是在扩展方式上,要支持日益增长的需求当然要扩展。

要支持更多并发量,SQL数据库是纵向扩展,也就是说提高处理能力,使用速度更快速的计算机,这样处理相同的数据集就更快了。

因为数据存储在关系表中,操作的性能瓶颈可能涉及很多个表,这都需要通过提高计算机性能来客服。虽然SQL数据库有很大扩展空间,但最终肯定会达到纵向扩展的上限。而NoSQL数据库是横向扩展的。

而非关系型数据存储天然就是分布式的,NoSQL数据库的扩展可以通过给资源池添加更多普通的数据库服务器(节点)来分担负载。

3、对事务性的支持不同。

如果数据操作需要高事务性或者复杂数据查询需要控制执行计划,那么传统的SQL数据库从性能和稳定性方面考虑是你的最佳选择。SQL数据库支持对事务原子性细粒度控制,并且易于回滚事务。

虽然NoSQL数据库也可以使用事务操作,但稳定性方面没法和关系型数据库比较,所以它们真正闪亮的价值是在操作的扩展性和大数据量处理方面。

数据库操作方法

创建(使用)数据库:

我们创建了数据库 runoob:

 
  1. > use runoob

  2. switched to db runoob

  3. > db

  4. runoob

删除数据库

首先,查看所有数据库:

 
  1. > show dbs

  2. admin 0.000GB

  3. config 0.000GB

  4. local 0.000GB

  5. runoob 0.000GB

接下来我们切换到数据库 runoob:

 
  1. > use runoob

  2. switched to db runoob

  3. >

执行删除命令:
 

 
  1. > db.dropDatabase()

  2. { "dropped" : "runoob", "ok" : 1 }

最后,我们再通过 show dbs 命令数据库是否删除成功:

 
  1. > show dbs

  2. admin 0.000GB

  3. config 0.000GB

  4. local 0.000GB

删除集合

集合删除语法格式如下:

db.collection.drop()

以下实例删除了 runoob 数据库中的集合 site:

 
  1. > use runoob

  2. switched to db runoob

  3. > db.createCollection("runoob") # 先创建集合,类似数据库中的表

  4. > show tables # show collections 命令会更加准确点

  5. runoob

  6. > db.runoob.drop()

  7. true

  8. > show tables

  9. >

更新文档

 
  1. db.collection.update(

  2. <query>,

  3. <update>,

  4. {

  5. upsert: <boolean>,

  6. multi: <boolean>,

  7. writeConcern: <document>

  8. }

  9. )

参数说明:

  • query : update的查询条件,类似sql update查询内where后面的。
  • update : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
  • upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
  • multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
  • writeConcern :可选,抛出异常的级别。

只更新第一条记录:

db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );

全部更新:

db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );

只添加第一条:

db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );

全部添加进去:

db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );

全部更新:

db.col.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );

只更新第一条记录:

db.col.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );

查询文档

db.collection.find(query, projection)
  • query :可选,使用查询操作符指定查询条件
  • projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)。

实例

以下实例我们查询了集合 col 中的数据:

 
  1. > db.col.find().pretty()

  2. {

  3. "_id" : ObjectId("56063f17ade2f21f36b03133"),

  4. "title" : "MongoDB 教程",

  5. "description" : "MongoDB 是一个 Nosql 数据库",

  6. "by" : "菜鸟教程",

  7. "url" : "http://www.runoob.com",

  8. "tags" : [

  9. "mongodb",

  10. "database",

  11. "NoSQL"

  12. ],

  13. "likes" : 100

  14. }

实现商品增删改查的功能

其实具体的方法很简单只是把得到的数据放入html进行展示,只是有的时候会有些东西容易被忽略。

 
  1. const express=require('express');

  2. const app=express();

  3. const dao=require('./model/dao.js');

  4.  
  5. app.use('/',express.static('./www/form'));

  6. app.use('/public',express.static('./public/'));

  7.  
  8. app.get('/add',(req,res)=>{

  9. var obj={

  10. proname:req.query.proname,

  11. proprice:req.query.proprice

  12. }

  13. dao.insert('product','phone',obj,function(r){

  14. res.send(r);

  15. })

  16. })

  17. app.get('/del',(req,res)=>{

  18. var obj={

  19. proname:req.query.proname

  20. }

  21. dao.delete('product','phone',obj,(r)=>{

  22. res.send(r);

  23. })

  24. })

  25. app.get('/find',(req,res)=>{

  26.  
  27. dao.find('product','phone',(r)=>{

  28. res.send(r)

  29. },{},{},0,10)

  30. })

  31. app.get('/update',(req,res)=>{

  32. var obj={

  33. proname:req.query.proname,

  34. proprice:req.query.proprice

  35. }

  36. var updateStr={

  37. uponame:req.query.uponame,

  38. upoprice:req.query.upoprice

  39. }

  40. dao.update('product','phone',obj,updateStr,function(r){

  41. res.send(r);

  42. })

  43. })

  44. app.listen('8989');

增删改查的封装

 
  1. // 引入数据库包,可以在php中操作数据库

  2. const MongoClient=require('mongodb').MongoClient;

  3. // 数据库地址

  4. const url="mongodb://localhost:27017";

  5.  
  6. // 把数据库连接的操作,封装起来。

  7. function _connect(callback){

  8. // 连接上数据库

  9. //连接数据库是异步操作,不知道什么时候连接成功了。用到回调函数的概念

  10. MongoClient.connect(url,{ useUnifiedTopology: true }, function(err, db) {

  11. // 连接数据库成功

  12. if (err) throw err;

  13. // 说明连接数据库成功了 db代表连接成功以后返回的数据

  14. callback(db);

  15. });

  16. }

  17.  
  18. // module.exports导出数据

  19. module.exports.insert=function(dbname,col,myobj,callback){

  20. _connect(function(db){

  21. // db连接成功的数据

  22. // db.db('操作的数据库')

  23. var dbo = db.db(dbname);

  24. // 插入的数据

  25. // var myobj = { name: "菜鸟教程", url: "www.runoob" };

  26. // 选择的数据库.collection('集合班级').insertOne(数据,(err,r)=>{

  27. // 数据插入成功

  28. // })

  29.  
  30. // 一条数据是对象 insertOne 多条数据是数组 用insertmMany

  31. if(myobj instanceof Array){

  32. myobj=myobj

  33. }else{

  34. myobj=[myobj]

  35. }

  36. dbo.collection(col).insertMany(myobj, function(err,r) {

  37. if (err) throw err;

  38. db.close();

  39. // r得到的是成功插入数据的信息

  40.  
  41. callback(r)

  42. })

  43.  
  44. })

  45. }

  46. // 查询封装的时候,考虑是否需要分页是否需要排序

  47. // 需要书写函数参数的默认值,因为用户有可能不会书写

  48. module.exports.find=function(dbname,col,callback,myobj={},mysort={},myskip=0,mylimit=0){

  49. _connect(function(db){

  50. // 查询数据

  51. var dbo = db.db(dbname);

  52. // sort排序

  53. // skip跳过多少条数据

  54. // limit()限制取数据的数量

  55.  
  56. dbo.collection(col).find(myobj).sort(mysort).skip(myskip).limit(mylimit).toArray(function(err, result) { // 返回集合中所有数据

  57. if (err) throw err;

  58. console.log(result);

  59. db.close();

  60. callback(result);

  61. })

  62. })

  63. }

  64.  
  65.  
  66.  
  67. module.exports.update=function(dbname,col,myobj,updateObj,callback){

  68. _connect(function(db){

  69. var dbo = db.db(dbname);

  70. var updateStr = {$set: updateObj};

  71. // updateOne(查询条件,更改的数据)

  72. dbo.collection(col).updateOne(myobj, updateStr, function(err, res) {

  73. if (err) throw err;

  74. console.log("文档更新成功");

  75. db.close();

  76. callback(res)

  77. });

  78. })

  79. }

  80. module.exports.delete=function(dbname,col,myobj,callback){

  81. _connect(function(db){

  82. var dbo = db.db(dbname);

  83. // updateOne(查询条件,更改的数据)

  84. dbo.collection(col).deleteOne(myobj, function(err,obj) {

  85. if (err) throw err;

  86.  
  87. db.close();

  88. callback(obj);

  89. });

  90. })

  91.  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值